The most straightforward Java solution


  • 0
    public class Solution {
        public String addStrings(String num1, String num2) {
            int p1 = num1.length() - 1; 
            int p2 = num2.length() - 1; 
            int carry = 0; 
            StringBuilder sb = new StringBuilder(); 
            
            while(p1>=0 && p2 >=0){
                int cur = (num1.charAt(p1) - '0') + (num2.charAt(p2) - '0') + carry; 
                if(cur>=10){
                    carry = 1; 
                    cur-=10; 
                }else{
                    carry = 0; 
                }
                sb.insert(0,cur); 
                p1--; p2--;
            }
            
            if(p2>=0){
                p1 = p2; 
                num1 = num2; 
            }
            
            while(p1>=0 || carry !=0){
                int cur = ((p1>=0) ? (num1.charAt(p1) - '0') : 0 ) + carry; 
                if(cur>=10){
                    carry = 1; 
                    cur-=10; 
                }else{
                    carry = 0; 
                }
                sb.insert(0,cur);
                p1--; 
            }
            return sb.toString(); 
        }
    }
    

Log in to reply
 

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