<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">以前看到过这样一个面试题,大体意思是:计算两个超大的数字[远超出long能表示的范围]相加,并打印结果?</span>
今天群里又有人在说这个问题,想想曾经看到面试题的时候不会做,现在思考了一下就来试试,结果轻而易举搞定了~~~~PS:是不是代码敲多了,自然就懂了?搜噶~~
这是第一次写的,大体可以用,但是运算的时候用了强制类型转换,效率不高,后面又稍微优化了一点点
public static String add(String digit1, String digit2) { String result = ""; char[] s1 = digit1.toCharArray(); char[] s2 = digit2.toCharArray(); char[] jg = new char[Math.max(s1.length, s2.length) + 1]; int carry = 0;// 表示进位 for (int i = 0; i < jg.length; i++) { int a1 = 0; int a2 = 0; if (s1.length - 1 - i >= 0) { a1 = Integer.parseInt("" + s1[s1.length - 1 - i]); } if (s2.length - 1 - i >= 0) { a2 = Integer.parseInt("" + s2[s2.length - 1 - i]); } int a = a1 + a2 + carry; if (a >= 10) { carry = 1; a = a - 10; } else { carry = 0; } jg[jg.length - 1 - i] = ("" + a).charAt(0); } for (int i = 0; i < jg.length; i++) { if (i == 0 && jg[i] == '0') { } else { result += jg[i]; } } return result; }
public static String add2(String digit1, String digit2) { String result = ""; char[] s1 = digit1.toCharArray(); char[] s2 = digit2.toCharArray(); char[] jg = new char[Math.max(s1.length, s2.length) + 1];// 结果数组比最常参数再长一位 int carry = 0;// 表示进位 for (int i = 0; i < jg.length; i++) { char a1 = '0'; char a2 = '0'; if (s1.length - 1 - i >= 0) { a1 = s1[s1.length - 1 - i]; } if (s2.length - 1 - i >= 0) { a2 = s2[s2.length - 1 - i]; } if (a1 < '0' || a1 > '9' || a2 < '0' || a2 > '9') { throw new RuntimeException("Parameters can only contain Numbers."); } char a = (char) (a1 + a2 - '0' + carry); if (a > '9') { carry = 1; a = (char) (a - 10); } else { carry = 0; } jg[jg.length - 1 - i] = a; } for (int i = 0; i < jg.length; i++) { if (i == 0 && jg[i] == '0') { } else { result += jg[i]; } } return result; }
跑了N次,最慢的时候用时2ms
原文地址:http://blog.csdn.net/lijunhuayc/article/details/42915883