Created
September 18, 2018 04:06
-
-
Save ShellBin/a10ff6b5d38c5f77fca3fe9d430e5968 to your computer and use it in GitHub Desktop.
String add
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String addStrings(String num1, String num2) { | |
String longString = null; | |
String shortSting = null; | |
if (num1.length() >= num2.length()) { | |
longString = num1; | |
shortSting = num2; | |
} else { | |
longString = num2; | |
shortSting = num1; | |
} | |
int big = longString.length(); | |
int small = shortSting.length(); | |
int carry = 0; | |
char[] ra = new char[big + 1]; | |
for (int i = 0; i < small; i++) { | |
int b = Character.getNumericValue(longString.charAt(big - i - 1)); | |
int s = Character.getNumericValue(shortSting.charAt(small - i - 1)); | |
ra[big - i] = Character.forDigit((b + s + carry) % 10, 10); | |
carry = (b + s + carry) / 10; | |
} | |
for (int i = 0; i < (big - small); i++) { | |
int b = Character.getNumericValue(longString.charAt(big - small - i - | |
1)); | |
ra[big - small - i] = Character.forDigit((b + carry) % 10, 10); | |
carry = (b + carry) / 10; | |
} | |
if (carry != 0) { | |
ra[0] = Character.forDigit(carry % 10, 10); | |
} | |
String ret = new String(ra).trim(); | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment