Problem Description
Read in two numbers in the form of a string, write a function to calculate their sum, and return it in the form of a string.
(The length of the string is not greater than 100000, and it is guaranteed that the string is only composed of 10 characters from '0' to '9')
Input description:
Input two string format numbers
Output description:
output the sum of numbers
Example
Example 1
Enter
"1", "99"
Output
"100"
Solutions
analysis
- Handle sequentially from the end to the front, handle the case of carry, need to handle the case of addition and exceeding the maximum number of string digits
method
- Through the loop to process sequentially from the end to the front, handle the case of carry, need to deal with the case of addition and exceeding the maximum number of string digits
Code
// 思路1
public class Solution {
public String solve (String s, String t) {
// write code here
if (s == null && s.length() == 0) {
return t;
}
if (t == null && t.length() == 0) {
return s;
}
if (s.length() < t.length()) {
String temp = s;
s = t;
t = temp;
}
int temp = 0;
int i = s.length() - 1, j = t.length() - 1;
char[] result = new char[s.length()];
while (i >= 0 && j >= 0) {
int a = s.charAt(i) - '0';
int b = t.charAt(j) - '0';
int c = a + b + temp;
if (c >= 10) {
temp = c / 10;
c %= 10;
} else {
temp = 0;
}
result[i] = (char) ('0' + c);
i--;
j--;
}
while (i >= 0) {
int a = s.charAt(i) - '0';
int c = a + temp;
if (c >= 10) {
temp = c / 10;
c %= 10;
} else {
temp = 0;
}
result[i] = (char) ('0' + c);
i--;
}
String val = new String(result);
if (temp > 0) {
return String.valueOf(temp) + val;
}
return val;
}
}
If you want to test, you can go directly to the link of Niuke.com to do the test