给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
let addStrings = (num1, num2) => {
let res = ''
let carry = 0, i = num1.length - 1, j = num2.length - 1
while (carry === 1 || i >= 0 || j >= 0) {
let x = i < 0 ? 0 : num1[i--] - '0'
let y = j < 0 ? 0 : num2[j--] - '0'
res += Math.floor((x + y + carry) % 10)
carry = Math.floor((x + y + carry) / 10)
}
return res.split("").reverse().toString()
}
console.log(addStrings('123', '123'))
func addStrings(num1 string, num2 string) string {
reverseStr := func (s string) string {
runes := []rune(s)
i, j := 0, len(runes) - 1
for i < j {
runes[i], runes[j] = runes[j], runes[i]
i++
j--
}
return string(runes)
}
x := 0
y := 0
carry := 0
i, j := len(num1) - 1, len(num2) - 1
var res string
for carry == 1 || i >= 0 || j >= 0 {
if i < 0 {
x = 0
} else {
x, _ = strconv.Atoi(string(num1[i]))
}
if j < 0 {
y = 0
} else {
y, _ = strconv.Atoi(string(num2[j]))
}
res += strconv.Itoa((x + y + carry) % 10)
carry = (x + y + carry) / 10
i--
j--
}
return reverseStr(res)
}
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder str = new StringBuilder();
int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
while (carry == 1 || i >= 0 || j >= 0) {
int x = i < 0 ? 0 : num1.charAt(i--) - '0';
int y = j < 0 ? 0 : num2.charAt(j--) - '0';
str.append((x + y + carry) % 10);
carry = (x + y + carry) / 10;
}
return str.reverse().toString();
}
}