LeetCode – 415. Add Strings

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.

 

public class Solution {
    public String addStrings(String num1, String num2) {
        int n = num1.length() -1;
        int m = num2.length() -1;
        int flag = 0;
        String result = new String();
        while(n>=0 || m>=0){
            int tmp = flag;
            if(n >=0){
                tmp+=(num1.charAt(n) - '0');
            }
            if(m >=0){
                tmp+=(num2.charAt(m) - '0');
            }
            if(tmp>9){
                flag = 1;
                tmp = tmp-10;
            }
            else{
                flag=0;
            }
            result = tmp + result;
            n--;
            m--;
        }
        if(flag ==1){
            result = "1" +result;
        }
        return result;
    }
}

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。