以字符串的形式给出两个非负整数 num1
和 num2
,返回 num1
和 num2
的和。
样例
给定 num1 = "123"
,num2 = "45"
返回 "168"
解题思路:
按位相加即可。注意最后的进位需要考虑。
public class Solution {
/**
* @param num1: a non-negative integers
* @param num2: a non-negative integers
* @return: return sum of num1 and num2
*/
public String addStrings(String num1, String num2) {
// write your code here
char[] nums1 = num1.toCharArray();
char[] nums2 = num2.toCharArray();
StringBuilder sb = new StringBuilder();
int cnt = 0;
int i=nums1.length-1, j=nums2.length-1;
while(i >=0 || j >= 0){
while(i >=0 && j >= 0){
int temp = nums1[i] - '0' + nums2[j] - '0' + cnt;
sb.append(temp%10);
cnt = temp / 10;
i--;
j--;
}
while(i >= 0){
int temp = nums1[i] - '0' + cnt;
sb.append(temp%10);
cnt = temp / 10;
i--;
}
while(j >= 0){
int temp = nums2[j] - '0' + cnt;
sb.append(temp%10);
cnt = temp / 10;
j--;
}
}
if(cnt != 0)
sb.append(cnt);
return sb.reverse().toString();
}
}