Easy Understanding Java Solution


  • 0
    I
    public class Solution {
        public String addStrings(String num1, String num2) {
            StringBuilder sb = new StringBuilder();
            int carry=0;
            int idx1=num1.length()-1;
            int idx2=num2.length()-1;
            while(idx1>=0&&idx2>=0){
                char c1= num1.charAt(idx1);
                char c2= num2.charAt(idx2);
                int v1= c1-'0';
                int v2= c2-'0';
                int q= (v1+v2+carry)%10;
                carry= (v1+v2+carry)/10;
                sb.insert(0,q);
                idx1--;
                idx2--;
            }
            while(idx1>=0){
                char c1= num1.charAt(idx1);
                int v1= c1-'0';
                int q= (v1+carry)%10;
                carry= (v1+carry)/10;
                sb.insert(0,q);
                idx1--;
            }
            
            while(idx2>=0){
                char c2= num2.charAt(idx2);
                int v2= c2-'0';
                int q= (v2+carry)%10;
                carry= (v2+carry)/10;
                sb.insert(0,q);
                idx2--;
            }
            if(carry==1)
            sb.insert(0,1);
            return sb.toString();
        }
    }
    

Log in to reply
 

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