Add Strings
来源:互联网 发布:mac pro 常用快捷键 编辑:程序博客网 时间:2024/05/17 08:54
Given two non-negative numbers 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.
思路,就是加法,保持进位,注意是从最后的char开始加的。
public class Solution { public String addStrings(String num1, String num2) { if(num1 == null && num2 == null) return null; if(num1 != null && num2 == null) return num1; if(num1 == null && num2 != null) return num2; StringBuilder sb = new StringBuilder(); int i=0; int j=0; int carry = 0; while(i<num1.length() || j<num2.length() || carry != 0){ int val1 = 0; if(i<num1.length()){ val1 = num1.charAt(num1.length()-1-i)-'0'; i++; } int val2 = 0; if(j<num2.length()){ val2 = num2.charAt(num2.length()-1-j)-'0'; j++; } int sum = val1 + val2 + carry; sb.insert(0, sum % 10); carry = sum / 10; } return sb.toString(); }}
0 0
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- Add Strings
- 415. Add Strings
- Leetcode 415 Add Strings
- Leetcode-415. Add Strings
- 415. Add Strings
- leetcode_415 Add Strings
- 415 add strings
- LeetCode[415] Add Strings
- 415. Add Strings
- LeetCode #415: Add Strings
- 415. Add Strings
- 415. Add Strings
- JavaScript--全选、全不选、反选、无刷新删除、批量删除、即点即改入库(在yii框架中操作)
- Behavior Designer
- android 不同drawable文件对应的dpi值,和所放图片分辨率
- picasso-强大的Android图片下载缓存库
- openwrt学习总结
- Add Strings
- 数据挖掘十大算法之—C4.5
- HDU 1237 简单计算器
- Java Web技术经验总结(二)
- Leetcode 309. Best Time to Buy and Sell Stock with Cooldown
- Android中的Https网络请求get和post
- python中方法(函数)的命名规则及调用
- 对于c#中代理的理解
- Thinkphp 中eq,neq,gt,lt等表达式缩写