In: Computer Science
Write a function addStrings(string1, string2) that takes in two decimals as strings and returns a string of their sum. *Simply converting strings to numbers and adding them together isn’t acceptable.* The program must be able to handle large decimals.
Be sure to touch on these when solving for the solution:
Please do the solution in either JavaScript or Ruby so that I can understand better.
// let testCase_string1 = '3.92';
// let testCase_string2 = '0.09';
// let testCase2_string1 = '103.00000000909';
// let testCase2_string2 = '0.0000000019101';
// let testCase3_string1 = '1099.999999999990001';
//let testCase3_string2 = '10000000.000000000000000201000';
Please find the code below:::
AddDecimalAsString.java
package classes3;
public class AddDecimalAsString {
static String addString(String
num1,String num2){
String
result="";
String number1[]
= num1.split("\\.");
String number2[]
= num2.split("\\.");
if(number1[0].length()>number2[0].length()){
String zeros="";
for(int
i=0;i<number1[0].length()-number2[0].length();i++){
zeros +="0";
}
number2[0] = zeros+number2[0];
}else
if(number2[0].length()>number1[0].length()){
String space="";
for(int
i=0;i<number2[0].length()-number1[0].length();i++){
space +="0";
}
number1[0] = space+number1[0];
}
if(number1[1].length()>number2[1].length()){
String zeros="";
for(int
i=0;i<number1[1].length()-number2[1].length();i++){
zeros +="0";
}
number2[1] = number2[1]+zeros;
}else
if(number2[1].length()>number1[1].length()){
String space="";
for(int
i=0;i<number2[1].length()-number1[1].length();i++){
space +="0";
}
number1[1] = number1[1]+space;
}
num1 =
number1[0]+"."+number1[1];
num2 =
number2[0]+"."+number2[1];
System.out.println("Number 1 : "+num1);
System.out.println("Number 2 : "+num2);
int
d1,d2,res,car=0;
for(int
i=num1.length()-1;i>=0;i--){
d1=0;
d2=0;
if(num1.charAt(i)=='.'){
result = "."+result;
continue;
}
d1 = Integer.parseInt(num1.charAt(i)+"");
d2 = Integer.parseInt(num2.charAt(i)+"");
res = d1+d2+car;
car = 0;
if(res>=10){
res = res-10;
car = 1;
}
result = res+result;
}
if(car!=0){
result = car+result;
}
//removing
trailing zeros
String finalres
="";
boolean num=
false;
for(int
i=result.length()-1;i>=0;i--){
if(result.charAt(i)=='0' && !num){
continue;
}else{
finalres =
result.charAt(i)+finalres;
num = true;
}
}
return
finalres;
}
public static void main(String[]
args) {
System.out.println("\n\nReturned result is :
"+addString("1099.999999999990001","10000000.000000000000000201000"));
}
}
output: