leetcode[415]:Add Strings
2017-02-19 13:37
323 查看
【原题】
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
1.The length of both num1 and num2 is < 5100.
2.Both num1 and num2contains only digits 0-9.
3.Both num1 and num2 does not contain any leading zero.
4.You must not use any built-in BigInteger library or convert the inputs to integer directly.
【分析】
求两个字符串类型的数字之和
【Java】
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
1.The length of both num1 and num2 is < 5100.
2.Both num1 and num2contains only digits 0-9.
3.Both num1 and num2 does not contain any leading zero.
4.You must not use any built-in BigInteger library or convert the inputs to integer directly.
【分析】
求两个字符串类型的数字之和
【Java】
public class Solution { public String addStrings(String num1, String num2) { int len1=num1.length()-1; int len2=num2.length()-1; StringBuilder sb=new StringBuilder(); int sum=0,carry=0; while(len1>=0 || len2>=0) { int first=len1>=0?num1.charAt(len1)-'0':0; int second=len2>=0?num2.charAt(len2)-'0':0; sum=carry+first+second; if(sum<=9){ sb.insert(0,sum); sum=0; carry=0; } else { sb.insert(0,sum%10); sum=0; carry=1; } len1--; len2--; } if(carry==1)sb.insert(0,"1"); return sb.toString(); } }
相关文章推荐
- 【leetcode】415 Add Strings
- 【LeetCode】415 Add Strings (java实现)
- LeetCode 415 Add Strings
- Leetcode 415 Add Strings
- Sum—LeetCode-415 Add Strings
- leetcode_415 Add Strings
- LeetCode[415] Add Strings
- [LeetCode 415] Add Strings(Python)
- leetcode-415-Add Strings
- 【LeetCode】415 Add Strings (java实现)
- LeetCode Add Strings(大整数加法)
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- LeetCode: Add Strings
- 415. Add Strings
- LeetCode:Add Strings
- leetcode[Add Strings]//待整理多种解法