title
Title description: Given two non-negative integers num1 and num2 in the form of strings, calculate their sum.
prompt:
- The length of num1 and num2 are both less than 5100
- Both num1 and num2 only contain numbers 0-9
- Neither num1 nor num2 contains any leading zeros
- You cannot use any built-in BigInteger library, nor can you directly convert the input string to integer form
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/add-strings/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Traverse the string
First, a statement string Result last return value, it is declared I initial value 0, addone to carry the initial value is 0, firstNum and secondNum respectively num1 and num2 current index bit, and then start to traverse the num1 and num2 , the processing process is as follows:
- If i does not exceed the num1 and num2 length, respectively the num1 and num2 assignment numbers current index to firstNum and secondNum , otherwise firstNum and secondNum assignment Is 0;
- Then calculate
firstNum + secondNum + addOne
result is sum ;- If sum greater than 9, carry is required, addOne is reset to 1, and
sum-10
added to the front of the string of result- If sum less than 9, there is no need to carry, addOne is reset to 0, and
sum
added to the front of the string of result- i plus 1.
Finally, it is judged that addOne is 1, then addOne added to the front of result
Finally, return the result of string addition.
/**
* @Author: ck
* @Date: 2021/9/29 8:34 下午
*/
public class LeetCode_415 {
public static String addStrings(String num1, String num2) {
String result = "";
// addOne为进位
int i = 0, addOne = 0, firstNum = 0, secondNum = 0;
while (i < num1.length() || i < num2.length()) {
if (i < num1.length()) {
// num1中当前位的数字
firstNum = num1.charAt(num1.length() - 1 - i) - '0';
} else {
firstNum = 0;
}
if (i < num2.length()) {
// num2中当前位的数字
secondNum = num2.charAt(num2.length() - 1 - i) - '0';
} else {
secondNum = 0;
}
int sum = firstNum + secondNum + addOne;
if (sum > 9) {
result = (sum - 10) + result;
addOne = 1;
} else {
result = sum + result;
addOne = 0;
}
i++;
}
if (addOne == 1) {
result = 1 + result;
}
return result;
}
public static void main(String[] args) {
// 期望输出: 533
System.out.println(addStrings("456", "77"));
}
}
[Daily Message] Honesty is the mother of life, and pragmatism is the way to success.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。