上次屁颠屁颠的跑了1k多公里去ucweb面试,本来自我感觉还不错的,可是还是很郁闷得就给打回来了…… 其中有个笔试题是求两个大数(比如100位)的和,我当时知道怎么做,思路也没问题,但是在纸上划的时候估计有些细节没处理好,比如判断输入等。回来后自己重新做了一遍,把它贴出来共享,奉献给即将面试的兄弟伙,有什么问题请拍砖。
-
-
-
-
-
- public class BigInt {
-
-
-
-
- public static void main(String[] args) {
- BigInt b = new BigInt();
- b.add("999", "999");
- }
-
- public String add(String a, String b) {
-
- if (!a.matches("\\d+") || !a.matches("\\d+")) {
- return null;
- }
- final int BASE = 10;
- int lenA = a.length();
- int lenB = b.length();
- int maxLen, partialSum, carry = 0;
- maxLen = (lenA > lenB) ? lenA : lenB;
- StringBuffer sum = new StringBuffer();
- int temA, temB = 0;
- for (int i = 0; i < maxLen; i++) {
- if (i >= lenA) {
- temA = 0;
- } else {
- temA = Integer.valueOf(a.charAt(lenA - i - 1) - 48);
- }
- if (i >= lenB) {
- temB = 0;
- } else {
- temB = Integer.valueOf(b.charAt(lenB - i - 1) - 48);
- }
- partialSum = temA + temB + carry;
- carry = partialSum / BASE;
- sum.append(partialSum % BASE);
- }
- if (carry == 1)
- sum.append(carry);
- System.out.println(a + "+" + b + "=" + sum.reverse().toString());
- return sum.reverse().toString();
- }
- }
网络上还有另外一个版本:
- package test;
-
- public class VeryBigNumAdd {
-
- public static void main(String[] args) {
- VeryBigNumAdd vbn = new VeryBigNumAdd();
- String a = "123453243455535634535252345234677576252241234123523453664563634";
- String b = "123453243455535634535252345234677576252241234123523453664563634";
- String result = vbn.doAdd(a, b);
- System.out.println("result:" + result);
- }
-
- String doAdd(String a, String b) {
- String str = "";
- int lenA = a.length();
- int lenB = b.length();
- int maxLen = (lenA > lenB) ? lenA : lenB;
- int minLen = (lenA < lenB) ? lenA : lenB;
- String strTmp = "";
- for (int i = maxLen - minLen; i > 0; i--) {
- strTmp += "0";
- }
-
- if (maxLen == lenA) {
- b = strTmp + b;
- } else
- a = strTmp + a;
- int JW = 0;
- for (int i = maxLen - 1; i >= 0; i--) {
- int tempA = Integer.parseInt(String.valueOf(a.charAt(i)));
- int tempB = Integer.parseInt(String.valueOf(b.charAt(i)));
- int temp;
- if (tempA + tempB + JW >= 10 && i != 0) {
- temp = tempA + tempB + JW - 10;
- JW = 1;
- } else {
- temp = tempA + tempB + JW;
- JW = 0;
- }
- str = String.valueOf(temp) + str;
- }
- return str;
- }
- }
这又是一个版本:
|