问题描述:
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
手工将字符串型的正整数相加。
思路:
取出每一位,加和确定carryover,然后完成相加。如果最后一位完成后carryover不是零,则手动添上一位
代码一次过:
class Solution {
public String addStrings(String num1, String num2) {
int pt1 = num1.length()-1;
int pt2 = num2.length()-1;
String ans = "";
int bit1=0;
int bit2=0;
int carryover=0;
while((pt1>=0)||(pt2>=0)){
int thisBit = 0;
if(pt1>=0){
bit1=num1.charAt(pt1)-'0';
}
else{
bit1=0;
}
if(pt2>=0){
bit2=num2.charAt(pt2)-'0';
}
else{
bit2=0;
}
thisBit=bit1+bit2+carryover;
if(thisBit>9){
thisBit=thisBit%10;
carryover=1;
}
else{
carryover=0;
}
ans=String.valueOf(thisBit)+ans;
pt1--;
pt2--;
}
if (carryover==1){
ans="1"+ans;
}
return ans;
}
}