LeetCode(八)415. Add Strings
来源:互联网 发布:汽配软件 编辑:程序博客网 时间:2024/06/16 13:34
题目要求如下
Given two non-negative integers num1 and num2 represented as
string, return the sum of num1 and num2.Note:
The length of both num1 and num2 is < 5100. Both num1 and num2
contains only digits 0-9. Both num1 and num2 does not contain any
leading zero. You must not use any built-in BigInteger library or
convert the inputs to integer directly.
两个数相加,考虑进位问题可以使用一个进位数来判断是否进位,处理字符串转换为char[]比较方便。
public class Solution { public String addStrings(String num1, String num2) { int i = num1.length() - 1; int j = num2.length() - 1; int carry = 0; char[] num1Array = num1.toCharArray(); char[] num2Array = num2.toCharArray(); StringBuilder sb = new StringBuilder(); while (i >= 0 || j >= 0 || carry == 1) { int a = i >= 0 ? (num1Array[i--] - '0') : 0; int b = j >= 0 ? (num2Array[j--] - '0') : 0; int sum = a + b + carry; sb.insert(0, sum % 10); carry = sum / 10; } return sb.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
- Battleships in a Board问题及解法
- 虚拟机类加载机制
- python处理要素类与excel关联的数据
- 全栈工程师
- 菜单的利用以及侧拉栏的使用
- LeetCode(八)415. Add Strings
- 交互式QGraphicsView(平移/缩放/旋转)
- 命令模式
- RXAndroid2.0初学习二
- [java]35个java性能优化总结
- 分别实现数字时钟和日历的js代码
- POJ1741-树的分治&树的重心&树上的路径问题-Tree
- thinkphp redis保存token
- DQN改进