415. Add Strings

class Solution {
    public String addStrings(String num1, String num2) {
      int i = num1.length() - 1;
      int j = num2.length() - 1;
      StringBuilder sb = new StringBuilder();
      int carry = 0;
      
      while (i >= 0 || j >= 0){
        int sum = 0;
        if(i >= 0){
          sum += num1.charAt(i) - '0';
          i--;
        }
        if(j >= 0){
          sum += num2.charAt(j) - '0';
          j--;
        }
        sum += carry;
        sb.append(sum % 10);
        carry = sum / 10;
      }
      if( carry != 0){
        sb.append(carry);
      }
      
      return sb.reverse().toString();
    
    }
}

 

This one is very similar to add binary , pretty much the same 

The only difference is % 10, /10

 

When the two strings are exhausted, need to check if the carry is non zero, in the case 87 + 87 = 174 

 

The carry is 1. 

I think this is same as add binary , the carry can only be I or 0. 

 

 

Reverse stringbuilder and change it to string 

 

 

 

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.

 

posted on 2018-07-18 09:45  猪猪&#128055;  阅读(109)  评论(0)    收藏  举报

导航