Leetcode 415. Add Strings
来源:互联网 发布:知乎经典回复 编辑:程序博客网 时间:2024/06/08 05:01
Leetcode 415. Add Strings
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution { public String addStrings(String num1, String num2) { if(num1.length() < num2.length()) { // 让num1始终为较长的那个字符串 String temp = num1; num1 = num2; num2 = temp; } int len1 = num1.length(); int len2 = num2.length(); num1 = new StringBuilder(num1).reverse().toString(); //逆序 num2 = new StringBuilder(num2).reverse().toString(); StringBuilder sb = new StringBuilder(); int carry = 0; // 进位 for(int i = 0 ; i < len1; i++) { int a = num1.charAt(i) - '0'; int b = (i < len2) ? num2.charAt(i) - '0' : 0; int r = a + b + carry; // 别忘了加上进位 if(r >= 10) { r %= 10; carry = 1; }else { carry = 0; } sb.append(r); } if(carry == 1) sb.append(carry); // 如果最后还有进位,别忘了加上 return sb.reverse().toString(); }}
阅读全文
0 0
- Leetcode-415. Add Strings
- LeetCode 415. Add Strings
- [LeetCode]--415. Add Strings
- LeetCode 415. Add Strings
- LeetCode 415. Add Strings
- LeetCode 415. Add Strings
- leetcode 415. Add Strings
- 【LeetCode】 415. Add Strings
- LeetCode 415. Add Strings
- Leetcode 415. Add Strings
- LeetCode - 415. Add Strings
- LeetCode 415. Add Strings
- Leetcode 415. Add Strings
- Leetcode-415. Add Strings
- LeetCode-415. Add Strings
- leetcode 415. Add Strings
- [leetcode]415. Add Strings
- 【Leetcode】415. Add Strings
- 自勉
- python 连接数据库执行sql 查询
- 647. Palindromic Substrings 回文子串
- 在python上操作MySQL数据库
- 自定义ToolBar
- Leetcode 415. Add Strings
- 初始化与清理
- Git本地项目添加到远程代码库
- Parameter 'offset' not found. Available parameters are [arg1, arg0, param1, param2]
- html id 选择器和 class 选择器
- 30 多年的软件经验,总结出 10 个编写出更好代码的技巧
- 各种加密和解密算法的实现
- 图像处理与计算机视觉的经典书籍
- JAVA的免费天气API接口调用示例