Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both
num1andnum2is < 5100. - Both
num1andnum2Contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or Convert the inputs to integers 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; } } This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:
Original author:Jake Tao,source:「LeetCode – 415. Add Strings」