(Easy) Add Strings LeetCode

Description:

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution:

import java.lang.Math;
class Solution {
    public String addStrings(String num1, String num2) {
        
        int smaller = num2.length()>num1.length()? num1.length(): num2.length();
        
        
        String sum = "";

        int dig = 0; 
        
        int i = num1.length()-1;
        
        int k = num2.length()-1;
        
        for(; (i>=0&&k>=0); i--, k--){
            
            int a =  Character.getNumericValue(num1.charAt(i));
            
            int b = Character.getNumericValue(num2.charAt(k));
            
            int value = (a+b+dig)%10;
            
            dig = (a+b+dig)/10;
            
            sum = sum + String.valueOf(value);
        }
        
        
       if(k>=0){
           for(int s = k; s>=0; s--){
               
               int b = Character.getNumericValue(num2.charAt(s));
               
                int value = (b+dig)%10;
            
                dig = (b+dig)/10;
            
                sum = sum + String.valueOf(value);
               
           }
       }
        
        else if(i >=0){
              for(int s = i; s>=0; s--){
               
               int a = Character.getNumericValue(num1.charAt(s));
               
                int value = (a+dig)%10;
            
                dig = (a+dig)/10;
            
                sum = sum + String.valueOf(value);
               
           }
        }
         if(dig > 0){
            
             sum = sum + String.valueOf(dig);
        }
        return reverse(sum);
        
    }
    public String reverse(String a){
        
        StringBuffer sb=new StringBuffer(a);
    
        String result =  sb.reverse().toString();
        
        return result;
    }
}

 

posted @ 2019-08-08 11:33  CodingYM  阅读(72)  评论(0编辑  收藏  举报