Easy Java solution


  • 1
    L
      public String addStrings(String num1, String num2) {
            StringBuilder builder = new StringBuilder();
            num1 = reverse(num1);
            num2 = reverse(num2);
            int len1=0;
            int len2=0;
            int carry=0;
            while(len1 < num1.length() || len2 < num2.length() || carry > 0) {
                int val = carry;
                if(len1<num1.length()) {
                    val += num1.charAt(len1)-'0';
                    len1++;
                }
                
                if(len2<num2.length()) {
                    val += num2.charAt(len2)-'0';
                    len2++;
                }
                carry = val/10;
                builder.append(val%10);
            }
            return builder.reverse().toString();
        }
        
        private String reverse(String s) {
            char[] arr = s.toCharArray();
            int i=0;
            int j=arr.length-1;
            while(j>i) {
                char c = arr[i];
                arr[i]=arr[j];
                arr[j] = c;
                i++;
                j--;
            }
            return new String(arr);
        }
    

Log in to reply
 

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