LeetCode 415. Add Strings
题目要求:
Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
这个方法比较复杂,当然效果也不是很高.
但是第一次想到的,首先写上,以后再继续优化
public class solution_new {
public String addStrings(String num1, String num2) {
if(num1.equals("0") && num2.equals("0")) return "0";
int[] arr = new int[Math.max(num1.length(), num2.length()) + 1];
StringBuffer sb = new StringBuffer();
arr = tonum(num1, num2);
if(arr[0] == 0) {
for(int i = 1;i < arr.length; i++) {
sb.append(arr[i]);
}
}
else {
for(int index : arr) {
sb.append(index);
}
}
return sb.toString();
}
public int[] tonum(String num1, String num2) {
//首先创建数组,进行数据的存储
int[] arr = new int[Math.max(num1.length(), num2.length())];
int i = Math.max(num1.length(), num2.length()) - 1;
for(int c = num1.length() - 1; c >= 0; c--) {
arr[i--] = num1.charAt(c) - '0' + 0;
}
i = Math.max(num1.length(), num2.length()) - 1;
for(int c = num2.length() - 1; c >= 0; c--) {
arr[i--] += num2.charAt(c) - '0' + 0;
}
//数组循环进位
for(i = arr.length - 1; i >= 0; i--) {
if(arr[i] > 9) {
if(i == 0) {
//整个数组进位
int[] arrx = new int[arr.length + 1];
arrx[0] = 1;
arr[i] -= 10;
System.arraycopy(arr, 0, arrx, 1, arr.length);
return arrx;
}
else {
//在原数组上进行改动
arr[i] -= 10;
arr[i-1] += 1;
}
}
}
return arr;
}
}