(Easy) Add Strings LeetCode
Description:
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.
Solution:
import java.lang.Math; class Solution { public String addStrings(String num1, String num2) { int smaller = num2.length()>num1.length()? num1.length(): num2.length(); String sum = ""; int dig = 0; int i = num1.length()-1; int k = num2.length()-1; for(; (i>=0&&k>=0); i--, k--){ int a = Character.getNumericValue(num1.charAt(i)); int b = Character.getNumericValue(num2.charAt(k)); int value = (a+b+dig)%10; dig = (a+b+dig)/10; sum = sum + String.valueOf(value); } if(k>=0){ for(int s = k; s>=0; s--){ int b = Character.getNumericValue(num2.charAt(s)); int value = (b+dig)%10; dig = (b+dig)/10; sum = sum + String.valueOf(value); } } else if(i >=0){ for(int s = i; s>=0; s--){ int a = Character.getNumericValue(num1.charAt(s)); int value = (a+dig)%10; dig = (a+dig)/10; sum = sum + String.valueOf(value); } } if(dig > 0){ sum = sum + String.valueOf(dig); } return reverse(sum); } public String reverse(String a){ StringBuffer sb=new StringBuffer(a); String result = sb.reverse().toString(); return result; } }