Add Strings

来源:互联网 发布:mac pro 常用快捷键 编辑:程序博客网 时间:2024/05/17 08:54

Given two non-negative numbers 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.

思路,就是加法,保持进位,注意是从最后的char开始加的。

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


0 0