415. Add Strings
阿新 • • 發佈:2018-10-27
public new return span num charat car pre style
stringbuilder加入到首位的話用insert
1 class Solution { 2 public String addStrings(String num1, String num2) { 3 if(num1.length() == 0) return num2; 4 if(num2.length() == 0) return num1; 5 int i = num1.length()-1; 6 int j = num2.length()-1; 7 int carry = 0;8 StringBuilder sb = new StringBuilder(); 9 while(i >= 0 || j >= 0){ 10 if(i < 0){ 11 int num = (num2.charAt(j) - ‘0‘ + carry) % 10; 12 carry = (num2.charAt(j) - ‘0‘ + carry) / 10; 13 sb.insert(0, num); 14 j--;15 }else if(j < 0){ 16 int num = (num1.charAt(i) - ‘0‘ + carry) % 10; 17 carry = (num1.charAt(i) - ‘0‘ + carry) / 10; 18 sb.insert(0, num); 19 i--; 20 }else{ 21 int num = (num1.charAt(i)- ‘0‘ + num2.charAt(j) - ‘0‘ + carry) % 10;22 carry = (num1.charAt(i)- ‘0‘ + num2.charAt(j) - ‘0‘ + carry) / 10; 23 sb.insert(0, num); 24 i--; 25 j--; 26 } 27 } 28 if(carry == 1){ 29 sb.insert(0, 1); 30 } 31 return sb.toString(); 32 33 } 34 }
415. Add Strings