标签:
方法一:
直接使用BigDecimal
方法二:字符串解析,注意stringBuilder.append(int x)这里的x最终会变成x字符串,而不是对应的char.
1 import java.math.BigDecimal; 2 import java.util.Scanner; 3 4 5 public class Main { 6 public static void main(String[] args) { 7 Scanner scanner=new Scanner(System.in); 8 String t1=scanner.next(); 9 String t2=scanner.next(); 10 System.out.println(getStr(t1, t2)); 11 scanner.close(); 12 } 13 14 public static String getStr(String a,String b) 15 { 16 int l=a.length(); 17 int s=b.length(); 18 String longString=l>s?a:b; 19 String shortString=l<=s?a:b; 20 l=longString.length(); 21 s=shortString.length(); 22 longString=new StringBuilder(longString).reverse().toString(); 23 shortString=new StringBuilder(shortString).reverse().toString(); 24 StringBuilder stringBuilder=new StringBuilder(); 25 boolean carry=false; 26 for(int i=0;i<s;i++) 27 { 28 char cl=longString.charAt(i); 29 char cs=shortString.charAt(i); 30 int il=cl-‘0‘; 31 int is=cs-‘0‘; 32 int nx=il+is+(carry?1:0); 33 if(nx>9) 34 { 35 carry=true; 36 stringBuilder.append((char)(‘0‘+nx-10)); 37 } 38 else { 39 carry=false; 40 stringBuilder.append((char)(‘0‘+nx)); 41 } 42 } 43 if(s==l && carry) 44 { 45 stringBuilder.append(‘1‘); 46 return stringBuilder.toString(); 47 } 48 String str=longString.substring(s,l); 49 for(int i=0;i<str.length();i++) 50 { 51 char c=str.charAt(i); 52 int nx=c-‘0‘+(carry?1:0); 53 if(nx>9) 54 { 55 carry=true; 56 stringBuilder.append((char)(‘0‘+nx-10)); 57 } 58 else { 59 carry=false; 60 stringBuilder.append((char)(‘0‘+nx)); 61 } 62 } 63 if(carry) 64 stringBuilder.append(‘1‘); 65 return stringBuilder.reverse().toString(); 66 } 67 }
标签:
原文地址:http://www.cnblogs.com/maydow/p/4782482.html