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();
    }
}

 

posted @ 2021-09-29 23:10  你的雷哥  阅读(64)  评论(0编辑  收藏  举报