Java 大数A+B

时间:2022-09-21 12:16:17
public class Solution {
public int length = 0; public Object[] numToArrays(int num) {
List<Integer> list = new ArrayList<Integer>();
while (num / 10 != 0) {
list.add((num) % 10);
num /= 10;
}
list.add(num % 10);
return list.toArray();
} public Object[] stringToArrays(String s1){
Object[] strs = new Integer[s1.toCharArray().length];
char[] chs = s1.toCharArray();
for(int i=strs.length-1;i>=0;i--){
strs[strs.length-1-i] = Integer.parseInt(String.valueOf(chs[i]));
}
return strs;
} public int[] bigSum(Object a, Object b) {
length = 0;
boolean isUp = false;
int[] result = new int[10000];
Object[] as = null;
Object[] bs = null;
if(a instanceof String){
as = stringToArrays((String)a);
bs = stringToArrays((String)b);
}else if(a instanceof Integer){
as = numToArrays((int)a);
bs = numToArrays((int)b);
} int i = 0;
int s = Math.min(as.length, bs.length);
Object[] larrays = as.length >= bs.length ? as : bs;
int l = larrays.length;
for (; i < s; i++) {
int c = (int) as[i] + (int) bs[i] + result[i];
if (c >= 10) {
// 进位,需增高一位
result[i + 1] += 1;
// 本位取余
result[i] = c % 10;
if (i + 1 >= s) {
isUp = true;
}
} else {
result[i] = c; }
length++;
}
int flag=0;
if (isUp){
length++;
flag=1;
}
isUp = false;
// 处理不等长
if (s != l) {
for (int k = length-flag; k < l; k++) {
int temp = result[k] + (int) larrays[k];
if (temp >= 10) {
result[k] = temp % 10;
result[k + 1] = 1;
if (k + 1 >= l) {
isUp = true;
}
} else {
result[k] = temp;
}
length++;
}
if(flag==1){
length--;
}
}
if (isUp)
length++;
return result;
} public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s = new Solution();
int[] list = s.bigSum("164455462456282903781237128937128937812937812973891272389456456222","123245445243512");
for (int i = s.length - 1; i >= 0; i--) {
System.out.print(list[i]);
}
} 输出:164455462456282903781237128937128937812937812973891395634901699734