您的位置:首页 > 编程语言 > Java开发

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:直接从低位开始求就行。参考大神的。。。。。。。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串 加法