Java Solution


  • 0
    M

    class Solution {
    public String addStrings(String num1, String num2) {
    int len1=num1.length();
    int len2=num2.length();
    int ans;
    String result="";
    int carry=0;
    if(len1>len2)
    {
    while(len2!=len1)
    {
    num2 ="0"+num2;
    len2++;
    }
    }
    else
    {
    while(len1!=len2)
    {
    num1="0"+num1;
    len1++;
    }
    }

        int i=len1-1;
        int j=len2-1;
        
       
        while(i>=0 && j>=0)
        {
          
                int x=Character.getNumericValue(num1.charAt(i));
                int y=Character.getNumericValue(num2.charAt(j));
           
                ans = x+y+carry;
                
                if(ans<=9)
                {
                    carry=0;
                    result= String.valueOf(ans) + result;
                  
                }
                   else{
                       carry=1;
                       if(i!=0){
                       String m=String.valueOf(ans);
                        result= m.charAt(1) + result;
                       }
                       if(i==0)
                       {
                         result= String.valueOf(ans) + result;
              
                       }
                   } 
         
             i--;
            j--;
        }
        
    return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.