逆向遍历过程模拟
nums1 和 nums2 ——>index1 = nums1.length,index2 - nums2.lengthwhile( index1>=0 || index2>=0 || carry != 0)x = index1>=0 ? nums1.charAt(i) - '0' : 0;y = index2>=0 ? nums1.charAt(i) - '0' : 0; int res = x+y+carry; 之后通过 StringBuffer ans = new StringBuffer(); sb.append(res%10)carry = res/10 ,之后 index1--; index2--;
class Solution {
public String addStrings(String num1, String num2) {
int index1 = num1.length()-1;
int index2 = num2.length()-1;
int carry = 0;
StringBuffer ans = new StringBuffer();
// 逆向遍历
while(index1>=0 || index2>=0 || carry!=0){
int x = index1>=0 ? num1.charAt(index1) - '0' :0;
int y = index2>=0 ? num2.charAt(index2) - '0' :0;
int res = x+y+carry;
ans.append(res%10);
carry = res/10;
index1--;
index2--;
}
ans.reverse();
return ans.toString();
}
}
public class addString {
public static String addTwo(String num1,String num2){
int index1 = num1.length()-1;
int index2 = num2.length()-1;
int carry = 0;
StringBuffer ans = new StringBuffer();
// 遍历
while( index1 >=0 || index2>= 0 || carry!=0){
int x = index1>=0 ? num1.charAt(index1)-'0' : 0;
int y = index2>=0 ? num2.charAt(index2)-'0' : 0;
int res = x+y+carry;
ans.append(res%10);
carry = res/10;
index1--;
index2--;
}
ans.reverse();
return ans.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入str1");
String input1 = sc.next();
System.out.println("输入str2");
String input2 = sc.next();
System.out.println("相加的结果是"+addTwo(input1,input2));
}
}