分享

java大数加法

 X的世界 2013-07-21
上次屁颠屁颠的跑了1k多公里去ucweb面试,本来自我感觉还不错的,可是还是很郁闷得就给打回来了……
     其中有个笔试题是求两个大数(比如100位)的和,我当时知道怎么做,思路也没问题,但是在纸上划的时候估计有些细节没处理好,比如判断输入等。回来后自己重新做了一遍,把它贴出来共享,奉献给即将面试的兄弟伙,有什么问题请拍砖。
  1.    
  2. /** 
  3.  * @author zhangyong 
  4.  *  
  5.  */  
  6. public class BigInt {  
  7.   
  8.     /** 
  9.      * @param args 
  10.      */  
  11.     public static void main(String[] args) {  
  12.         BigInt b = new BigInt();  
  13.         b.add("999""999");  
  14.     }  
  15.   
  16.     public String add(String a, String b) {  
  17.         //检查输入  
  18.         if (!a.matches("\\d+") || !a.matches("\\d+")) {  
  19.             return null;  
  20.         }  
  21.         final int BASE = 10;//10进制  
  22.         int lenA = a.length();//加数的长度  
  23.         int lenB = b.length();//被加数的长度  
  24.         int maxLen, partialSum, carry = 0;//大数的长度,和,进位  
  25.         maxLen = (lenA > lenB) ? lenA : lenB;  
  26.         StringBuffer sum = new StringBuffer();  
  27.         int temA, temB = 0;  
  28.         for (int i = 0; i < maxLen; i++) {  
  29.             if (i >= lenA) {  
  30.                 temA = 0;  
  31.             } else {  
  32.                 temA = Integer.valueOf(a.charAt(lenA - i - 1) - 48);  
  33.             }  
  34.             if (i >= lenB) {  
  35.                 temB = 0;  
  36.             } else {  
  37.                 temB = Integer.valueOf(b.charAt(lenB - i - 1) - 48);  
  38.             }  
  39.             partialSum = temA + temB + carry;  
  40.             carry = partialSum / BASE;  
  41.             sum.append(partialSum % BASE);  
  42.         }  
  43.         if (carry == 1)  
  44.             sum.append(carry);  
  45.         System.out.println(a + "+" + b + "=" + sum.reverse().toString());  
  46.         return sum.reverse().toString();  
  47.     }  
  48. }  

    网络上还有另外一个版本:
  1. package test;  
  2.   
  3. public class VeryBigNumAdd {  
  4.   
  5.     public static void main(String[] args) {  
  6.         VeryBigNumAdd vbn = new VeryBigNumAdd();  
  7.         String a = "123453243455535634535252345234677576252241234123523453664563634";  
  8.         String b = "123453243455535634535252345234677576252241234123523453664563634";  
  9.         String result = vbn.doAdd(a, b);  
  10.         System.out.println("result:" + result);  
  11.     }  
  12.   
  13.     String doAdd(String a, String b) {  
  14.         String str = "";  
  15.         int lenA = a.length();  
  16.         int lenB = b.length();  
  17.         int maxLen = (lenA > lenB) ? lenA : lenB;  
  18.         int minLen = (lenA < lenB) ? lenA : lenB;  
  19.         String strTmp = "";  
  20.         for (int i = maxLen - minLen; i > 0; i--) {  
  21.             strTmp += "0";  
  22.         }  
  23.         // 把长度调整到相同  
  24.         if (maxLen == lenA) {  
  25.             b = strTmp + b;  
  26.         } else  
  27.             a = strTmp + a;  
  28.         int JW = 0;// 进位  
  29.         for (int i = maxLen - 1; i >= 0; i--) {  
  30.             int tempA = Integer.parseInt(String.valueOf(a.charAt(i)));  
  31.             int tempB = Integer.parseInt(String.valueOf(b.charAt(i)));  
  32.             int temp;  
  33.             if (tempA + tempB + JW >= 10 && i != 0) {  
  34.                 temp = tempA + tempB + JW - 10;  
  35.                 JW = 1;  
  36.             } else {  
  37.                 temp = tempA + tempB + JW;  
  38.                 JW = 0;  
  39.             }  
  40.             str = String.valueOf(temp) + str;  
  41.         }  
  42.         return str;  
  43.     }  
  44. }  

   这又是一个版本:
  1. import java.util.ArrayList;  
  2. import java.util.Collections;  
  3.   
  4. public class VeryLongInt {  
  5.   
  6.     ArrayList digits;  
  7.   
  8.     // Postcondition: The VeryLongInt is empty.  
  9.     public VeryLongInt() {  
  10.         final int INITIAL_CAPACITY = 500;  
  11.         digits = new ArrayList(INITIAL_CAPACITY);  
  12.     } // default constructor  
  13.   
  14.     // Precondition: n >= 0.  
  15.     // Postcondition: The VeryLongInt has been initialized from the  
  16.     // not-very-long int n.  
  17.     public VeryLongInt(int n) {  
  18.         final int BASE = 10;  
  19.         digits = new ArrayList();  
  20.         do {  
  21.             digits.add(new Integer(n % BASE));  
  22.             n = n / BASE;  
  23.         } // while  
  24.         while (n > 0);  
  25.         // digits is now in reverse order, so we reverse:  
  26.         Collections.reverse(digits);  
  27.   
  28.     } // constructor  
  29.   
  30.     // Postcondition: The number of elements in the VeryLongInt has  
  31.     // been returned.  
  32.     public int size() {  
  33.         return digits.size();  
  34.     } // method size  
  35.   
  36.     // Precondition: The string s consists of a sequence of characters  
  37.     // with non-digit characters ignored.  
  38.     // There are no leading zeroes, except for 0  
  39.     // itself, which has a single '0'.  
  40.     // Postcondition: The VeryLongInt has been initialized from s.  
  41.     public VeryLongInt(String s) {  
  42.         final char LOWEST_DIGIT_CHAR = '0';  
  43.         final char HIGHEST_DIGIT_CHAR = '9';  
  44.         digits = new ArrayList(s.length());  
  45.         char c;  
  46.         int digit;  
  47.         for (int i = 0; i < s.length(); i++) {  
  48.             c = s.charAt(i);  
  49.             if ((LOWEST_DIGIT_CHAR <= c) && (c <= HIGHEST_DIGIT_CHAR)) {  
  50.   
  51.                 digit = c - LOWEST_DIGIT_CHAR;  
  52.                 digits.add(new Integer(digit));  
  53.             } // if a digit  
  54.         } // for  
  55.     } // constructor with string parameter  
  56.   
  57.     // Postcondition: The VeryLongInt has been returned as a string of digits.  
  58.     public String toString() {  
  59.         final String EMPTY_STRING = "";  
  60.         String s = EMPTY_STRING;  
  61.         for (int i = 0; i < digits.size(); i++)  
  62.             s += digits.get(i);  
  63.         return s;  
  64.   
  65.     } // method toString  
  66.   
  67.     // Postcondition: If i >= digits.size(), 0 has been returned; else  
  68.     // the ith least significant digit in digits has  
  69.     // been returned. The least significant digit is  
  70.     // the 0th least significant digit.  
  71.     private int least(int i) {  
  72.         if (i >= digits.size())  
  73.             return 0;  
  74.         else  
  75.             return ((Integer) (digits.get(digits.size() - i - 1))).intValue();  
  76.     } // least  
  77.   
  78.     // Postcondition: The VeryLongInt has been incremented by otherVeryLong.  
  79.     public void add(VeryLongInt otherVeryLong) {  
  80.         final int BASE = 10;  
  81.         int largerSize, partialSum, carry = 0;  
  82.         VeryLongInt sum = new VeryLongInt();  
  83.         if (digits.size() > otherVeryLong.digits.size())  
  84.             largerSize = digits.size();  
  85.         else  
  86.             largerSize = otherVeryLong.digits.size();  
  87.   
  88.         for (int i = 0; i < largerSize; i++) {  
  89.   
  90.             partialSum = least(i) + otherVeryLong.least(i) + carry;  
  91.             carry = partialSum / BASE;  
  92.             sum.digits.add(new Integer(partialSum % BASE));  
  93.   
  94.         } // for  
  95.   
  96.         if (carry == 1)  
  97.             sum.digits.add(new Integer(carry));  
  98.         Collections.reverse(sum.digits);  
  99.         digits = sum.digits;  
  100.     } // method add  
  101.   
  102.     // Postcondition: A copy of the calling object has been returned.  
  103.     public Object clone() {  
  104.         VeryLongInt temp = new VeryLongInt();  
  105.         temp.digits = (ArrayList) digits.clone();  
  106.         return temp;  
  107.     } // method clone  
  108.   
  109.     // Postcondition: true has been returned if the  
  110.     // value of the VeryLongInt is less than the value  
  111.     // of otherVeryLong. Otherwise, false  
  112.     // has been returned.  
  113.     public boolean less(VeryLongInt otherVeryLong) {  
  114.   
  115.         if (digits.size() < otherVeryLong.digits.size())  
  116.             return true;  
  117.         if (digits.size() > otherVeryLong.digits.size())  
  118.             return false;  
  119.         for (int i = 0; i < digits.size(); i++) {  
  120.             if (((Integer) (digits.get(i))).intValue() < ((Integer) (otherVeryLong.digits  
  121.                     .get(i))).intValue())  
  122.                 return true;  
  123.             if (((Integer) (digits.get(i))).intValue() > ((Integer) (otherVeryLong.digits  
  124.                     .get(i))).intValue())  
  125.                 return false;  
  126.         } // for  
  127.         return false// the two objects have the same value  
  128.     } // method less  
  129.   
  130.     // Postcondition: true has been returned if the value of the VeryLongInt  
  131.     // is greater than the value of otherVeryLong. Otherwise,  
  132.     // false has been returned.  
  133.     public boolean greater(VeryLongInt otherVeryLong) {  
  134.         return otherVeryLong.less(this);  
  135.     } // method greater  
  136.   
  137.     // Postcondition: true has been returned if the value of the VeryLongInt  
  138.     // is equal to the value of otherVeryLong. Otherwise,  
  139.     // false has been returned.  
  140.     public boolean equals(VeryLongInt otherVeryLong) {  
  141.         return !less(otherVeryLong) && !otherVeryLong.less(this);  
  142.     } // method equals  
  143.   
  144.     // Precondition: n > 0.  
  145.     // Postcondition: The calling object contains the nth Fibonacci  
  146.     // number.  
  147.     public void fibonacci(int n) {  
  148.         VeryLongInt previous = new VeryLongInt(1), current = new VeryLongInt(1), temp = new VeryLongInt();  
  149.         digits.clear();  
  150.         if (n <= 2)  
  151.             digits.add(new Integer(1));  
  152.         else {  
  153.             for (int i = 3; i <= n; i++) {  
  154.                 temp = (VeryLongInt) current.clone();  
  155.                 current.add(previous);  
  156.                 previous = temp;  
  157.             } // for  
  158.             digits = current.digits;  
  159.         } // else  
  160.   
  161.     } // method fibonacci  
  162.   
  163. // class VeryLongInt

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多