Friday, January 6, 2017

Leetcode--G家Airbnb--415. Add Strings(Math)

415. Add Strings
Easy
https://leetcode.com/problems/add-strings/

思路: add each str by char, sum added by 3steps: 1st inc 2nd num1[i] 3rd num[j]
          After looping, if extra inc left, append 1 to the sb

public class Solution {
    public String addStrings(String num1, String num2) {
        int m = num1.length(), n = num2.length();
        int len = m>n?m:n;
        StringBuilder sb = new StringBuilder();
        int inc = 0,i=m-1,j=n-1;
        while(i>=0||j>=0){
            int sum = inc;
            if(i>=0)sum += num1.charAt(i--)-'0';
            if(j>=0)sum += num2.charAt(j--)-'0';
            if(sum>=10){
                sb.append(sum - 10);
                inc = 1;
            }else{
                sb.append(sum);
                inc = 0;
            }
        }
        if(inc == 1) sb.append(1);//inc in sum
        return sb.reverse().toString();
    }
}

No comments:

Post a Comment