Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - 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; } }