(两个大数相加)

收集面试题(十一)(两个大数相加)

大数加法

Java代码   收藏代码
  1. /**  
  2.  * @param args  
  3.  */   
  4. public   static   void  main(String[] args) {  
  5.     BigInt b = new  BigInt();  
  6.     b.add("999999999999444599999999999999999" "99223333333223455559" );  
  7. }  
  8.   
  9. public  String add(String a, String b) {  
  10.     // 检查输入   
  11.     if  (!a.matches( "\\d+" ) || !a.matches( "\\d+" )) {  
  12.         return   null ;  
  13.     }  
  14.     final   int  BASE =  10 ; // 10进制   
  15.     int  lenA = a.length(); // 加数的长度   
  16.     int  lenB = b.length(); // 被加数的长度   
  17.     int  maxLen, partialSum, carry =  0 ; // 大数的长度,和,进位   
  18.     maxLen = (lenA > lenB) ? lenA : lenB;  
  19.     StringBuffer sum = new  StringBuffer();  
  20.     int  temA, temB =  0 ;  
  21.     for  ( int  i =  0 ; i < maxLen; i++) {  
  22.         if  (i >= lenA) {  
  23.             temA = 0 ;  
  24.         } else  {  
  25.             temA = Integer.valueOf(a.charAt(lenA - i - 1 ) -  48 );  
  26.         }  
  27.         if  (i >= lenB) {  
  28.             temB = 0 ;  
  29.         } else  {  
  30.             temB = Integer.valueOf(b.charAt(lenB - i - 1 ) -  48 );  
  31.         }  
  32.         partialSum = temA + temB + carry;  
  33.         carry = partialSum / BASE;  
  34.         sum.append(partialSum % BASE);  
  35.     }  
  36.     if  (carry ==  1 )  
  37.         sum.append(carry);  
  38.     System.out.println(a + " + "  + b +  " = "  + sum.reverse().toString());  
  39.     return  sum.reverse().toString();  

ASCII:
0:48
A:65
a:97

你可能感兴趣的:((两个大数相加))