Leetcode 415. Add Strings JAVA语言
2017-01-11 22:24
155 查看
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.题意:字符串做加法。但是不能用内置的函数直接做。
public class Solution { public String addStrings(String num1, String num2) { int i=num1.length()-1; int j=num2.length()-1; //http://blog.csdn.net/kingzone_2008/article/details/9220691 StringBuilder ret=new StringBuilder(); int carry=0; while(i>=0 || j>=0){ ///这里避免了两个字符串长度不一的情况下 int sum1=i>=0?num1.charAt(i--)-'0':0; int sum2=j>=0?num2.charAt(j--)-'0':0; int sum=sum1+sum2+carry; carry=sum/10; ret.append(sum%10); } if(carry>0){ ret.append(1); } return ret.reverse().toString(); } }PS:直接从低位开始求就行。参考大神的。。。。。。。。。。。
相关文章推荐
- Leetcode 344. Reverse String JAVA语言
- Leetcode 447. Number of Boomerangs JAVA语言
- leetcode 10: Triangle
- 【LeetCode】Pascal's Triangle II (杨辉三角)
- LeetCode: Reorder List
- LeetCode-Wildcard Matching
- LeetCode题目详解——Binary Tree Preorder Traversal
- LeetCode之Two Sum
- LeetCode--Spiral Matrix
- leetcode Pascal's Triangle
- https://leetcode.com/problems/trapping-rain-water/
- leetcode | Path Sum II
- House Robber II -- leetcode
- 139 Word Break [Leetcode]
- LeetCode -- Maximum Subarray
- LeetCode 231.power of two
- leetcode——328——Odd Even Linked List
- LeetCode 之 Sum Root to Leaf Numbers
- LeetCode 171. Excel Sheet Column Number
- leetcode:295. Find Median from Data Stream