415. 字符串相加_简单_模拟
class Solution { public String addStrings(String num1, String num2) { String value = ""; int dub = 0; //记录上次结果是否大于10 for(int i=1;i<=Math.max(num1.length(),num2.length());i++){ if(i>num2.length()){ int a1 = Integer.parseInt(num1.substring(num1.length()-i,num1.length()-i+1)); if(dub==1){ a1 ++; } dub = 0; if(a1>=10){ value += String.valueOf(a1%10); dub = 1; }else{ value += String.valueOf(a1); } } if(i>num1.length()){ int a2 = Integer.parseInt(num2.substring(num2.length()-i,num2.length()-i+1)); if(dub==1){ a2 ++; } dub = 0; if(a2>=10){ value += String.valueOf(a2%10); dub = 1; } else{ value += String.valueOf(a2); } } if(i<=num1.length() && i<=num2.length()){ int a1 = Integer.parseInt(num1.substring(num1.length()-i,num1.length()-i+1)); int a2 = Integer.parseInt(num2.substring(num2.length()-i,num2.length()-i+1)); int result= a1+a2; if(dub==1){ result++; } dub=0; if(result>=10){ value += String.valueOf(result%10); dub = 1; }else{ value += String.valueOf(result); dub = 0; } } } if(dub==1){ value+= "1"; } String a = ""; for(int i=0;i<value.length();i++){ a+= value.substring(value.length()-1-i,value.length()-i); } value = a; return value; } }
简单的写法
class Solution { public String addStrings(String num1, String num2) { StringBuilder sb = new StringBuilder(); int carry = 0, i = num1.length()-1, j = num2.length()-1; while(i >= 0 || j >= 0 || carry != 0){ if(i>=0) carry += num1.charAt(i--)-'0'; if(j>=0) carry += num2.charAt(j--)-'0'; sb.append(carry%10); carry /= 10; } return sb.reverse().toString(); } }
作者:你的雷哥
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。