字符串的是不将他们转化为整型后计算,而且一般我们给出的字符串可能特别长,长到我们转化为Double都无法计算,我们只能逐位计算,有进位则进位计算,如下:
//求出两个数字字符串的和 private String add(String str1, String str2) { StringBuilder sb = new StringBuilder(); char[] chars1 = str1.toCharArray(); char[] chars2 = str2.toCharArray(); int carry = 0;//进位 int c1 = chars1.length - 1, c2 = chars2.length - 1; while (c1 >= 0 || c2 >= 0 || carry != 0) { int n1 = c1 >= 0 ? chars1[c1] - '0' : 0; int n2 = c2 >= 0 ? chars2[c2] - '0' : 0; int sum = n1 + n2 + carry; int add = sum % 10; sb.append(add); carry = sum / 10; c1--; c2--; } return sb.reverse().toString(); }
//整数求和 private int add(int num1, int num2) { //当&为0的时候^为解 //当进位值为0的时候,我们的异或运算就是我们最终的答案 while (num2 != 0) { int temp = num1 & num2;//还需要进位多少 num1 = (num1 ^ num2);//当前值 num2 = temp << 1;//向前进位 } return num1; }