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 415. Add Strings JAVA语言
原文:http://fulin0532.blog.51cto.com/6233825/1891197