Skip to content

Instantly share code, notes, and snippets.

@aaphadke
Last active October 30, 2018 06:43
Show Gist options
  • Save aaphadke/5b38f38397a934f2b89f08ac4c119ff9 to your computer and use it in GitHub Desktop.
Save aaphadke/5b38f38397a934f2b89f08ac4c119ff9 to your computer and use it in GitHub Desktop.
private static void fb_add() {
String s1="5.4";
String s2="0.98";
String[] s1_array = s1.split(".");
String[] s2_array = s2.split(".");
String pre_s1=s1_array[0];
String pre_s2=s2_array[0];
String post_s1 = s1_array[1];
String post_s2 = s2_array[1];
StringBuilder out = new StringBuilder("");
int post_diff = post_s2.length()-post_s1.length();
int pre_diff = pre_s2.length()-pre_s1.length();
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int i=s1.length()-1;
int j=s2.length()-1;
int carry =0;
while(i>=0 || j>=0){
while(i!=j){
if(post_diff>0){
out.append(s2.charAt(j));
j--;
}
else if(post_diff<0){
out.append(s1.charAt(i));
i--;
}
}
if(c1[i]=='.' && c2[j]=='.'){
out.append('.');
i--;
j--;
continue;
}
int temp_sum = Character.getNumericValue(c1[i])+Character.getNumericValue(c2[j])+carry;
int sum = temp_sum %10;
carry = temp_sum / 10;
out.append(sum);
i--;
j--;
}
if(pre_diff>0){
int tmp = Character.getNumericValue(s2.charAt(j));
tmp = tmp +carry;
out.append(tmp);
} else if(pre_diff<0) {
int tmp = Character.getNumericValue(s1.charAt(i));
tmp = tmp +carry;
out.append(tmp);
}
if(carry>0){
out.append(carry);
}
System.out.print(out.reverse().toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment