leetcode415. 字符串相加
字符串 相加
2023-09-27 14:25:55 时间
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
注意:
num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
思路:模拟小学加法竖式计算即可,注意长度不同如何处理。
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder res = new StringBuilder("");
int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
while(i >= 0 || j >= 0){
int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
int tmp = n1 + n2 + carry;
carry = tmp / 10;
res.append(tmp % 10);
i--; j--;
}
if(carry == 1) res.append(1);
return res.reverse().toString();
}
}
相关文章
- python,如何获取字符串中的子字符串,部分字符串
- 1035 Password (20 分)【难度: 一般 / 知识点: 字符串 模拟】
- python实例 输出字符串和数字
- Python 代码库之unicode 编码与字符串之间相互转换
- js把数组转换为以逗号分隔的字符串
- JS代码把JSON字符串转换为对象,计算对象的长度并把它转换为数字类型,把转换的值相加减
- JS 对象(Object)和字符串(String)互转方法
- [LeetCode] 1234. Replace the Substring for Balanced String 替换子串得到平衡字符串
- [LeetCode] Special Binary String 特殊的二进制字符串
- [LeetCode] 438. Find All Anagrams in a String 找出字符串中所有的变位词