Last active
March 19, 2020 13:07
-
-
Save srsandy/bd022622458103d172bbee4a2edea8d5 to your computer and use it in GitHub Desktop.
Adding big numbers using Strings in java
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
public String Add(String input1, String input2) { | |
String ans = ""; | |
int len1 = input1.length(); | |
int len2 = input2.length(); | |
if(len1 < len2){ | |
String temp = input1; | |
input1 = input2; | |
input2 = temp; | |
} | |
len1 = input1.length(); | |
len2 = input2.length(); | |
int diff = len1 - len2; | |
int c = 0; | |
for(int i=len1 - 1, j=len2 - 1; j>=0 ; i--, j--) { | |
int sum = Character.getNumericValue(input2.charAt(j)) + Character.getNumericValue(input1.charAt(i)) + c; | |
c = (int)sum/10; | |
sum%=10; | |
ans = String.valueOf(sum) + ans; | |
} | |
for(int i = diff - 1; i>=0; i--) { | |
int sum = Character.getNumericValue(input1.charAt(i)) + c; | |
c = (int)sum/10; | |
sum%=10; | |
ans = String.valueOf(sum) + ans; | |
} | |
if(diff == 0) { | |
ans = String.valueOf(c) + ans; | |
} | |
if(c != 0) { | |
ans = String.valueOf(c) + ans; | |
} | |
int i = 0; | |
while (ans.charAt(i) == '0' && i<ans.length()-1) | |
i++; | |
StringBuffer sb = new StringBuffer(ans); | |
if(i == ans.length()) | |
return "0"; | |
sb.replace(0, i, ""); | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment