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 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」

145
0 0 145

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top