Question

Write a function addStrings(string1, string2) that takes in two decimals as strings and returns a string...

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:

  • Pad the right side
  • Pad the left side
  • Make sure string is same length by putting 0’s where it was missing (be careful w/ decimal points)
  • Make sure to remove trailing 0’s
  • Chunk out each step into it’s own function *NOT REQUIRED BUT CODE LOOKS CLEANER DOING SO*

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';

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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:

Add a comment
Know the answer?
Add Answer to:
Write a function addStrings(string1, string2) that takes in two decimals as strings and returns a string...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PYTHON The function longest that returns the longest of two strings. The function count_over that takes...

    PYTHON The function longest that returns the longest of two strings. The function count_over that takes a list of numbers and an integer nand returns the count of the numbers that are over n. The function bmi that takes two parameters height and weight and returns the value of the body mass index: a person's weight in kg divided by the square of their height in meters. def longest(string1, string2): """Return the longest string from the two arguments, if the...

  • Write a function valid_integers(strings) that takes a list of strings as a parameter and returns a...

    Write a function valid_integers(strings) that takes a list of strings as a parameter and returns a list of the integers that can be obtained by converting the strings to integers using an expression like int(string). Strings which cannot be converted in this way are ignored. Hint: the statement pass is a statement that does nothing when executed. For example: Test Result strings = ['123', '-39', '+45', 'x', 'COSC121', '123+', '12-3'] print(valid_integers(strings)) [123, -39, 45]

  • a. Write a function arrayToMap that takes an array of strings and returns a std::map<int, string>...

    a. Write a function arrayToMap that takes an array of strings and returns a std::map<int, string> such that the values in the map are the string values in the array of strings, and the keys in the map are the corresponding array indices of the string values. You may assume all necessary libraries have been included in your program and your solution must be syntactically correct in order to receive full credit. map<int, string> arrayToMap(string arr[], int arrSize) { b....

  • Write a function named words_in_both that takes two strings as parameters and returns a set of...

    Write a function named words_in_both that takes two strings as parameters and returns a set of the words contained in both strings. You can assume all characters are letters or spaces. Capitalization shouldn't matter: "to", "To", "tO", and "TO" should all count as the same word. The words in the set should be all lower-case. For example, if one string contains "To", and the other string contains "TO", then the set should contain "to". You can use Python's split() funciton,...

  • Write a function named words_in_both that takes two strings as parameters and returns a set of...

    Write a function named words_in_both that takes two strings as parameters and returns a set of the words contained in both strings. You can assume all characters are letters or spaces. Capitalization shouldn't matter: "to", "To", "tO", and "TO" should all count as the same word. The words in the set should be all lower-case. For example, if one string contains "To", and the other string contains "TO", then the set should contain "to". The file must be named: words_in_both.py...

  • in c++ 4. Include a function that adds two strings to make a third string. Write...

    in c++ 4. Include a function that adds two strings to make a third string. Write a program to do the following tasks: i. Create uninitialized string objects ii. Creates the objects with string constants. ii. Concatenates two strings properly iv. Displays a desired string object

  • Write a function that takes two arguments, both strings. Print "YES" if the second string argument...

    Write a function that takes two arguments, both strings. Print "YES" if the second string argument contains only characters found in the first string argument. Print "NO" if the second string argument contains characters not in the first. Here are some sample calls. In your program, call the function 3 times with the same arguments shown below. makeStr("hello", "") makeStr("hello", "olleloheloeloheloel") makeStr("hello", "olleloheloteloheloel") # YES # YES # NO

  • Write a function is_mirror(s) that takes as input a string s and returns True if s...

    Write a function is_mirror(s) that takes as input a string s and returns True if s is a mirrored string (i.e., a string that could have been produced by your mirror function) and False otherwise. Examples: >>> is_mirror('baconnocab') result: True >>> is_mirror('baconnoca') result: False Warning Your function should return a boolean value – either True or False, without any quotes around them. If you see quotes around the result when you make the calls above from the console, you must...

  • Problem 3 Write a function named repeat_words that takes two string parameters: 1. in_file: the name...

    Problem 3 Write a function named repeat_words that takes two string parameters: 1. in_file: the name of an input file that exists before repeat_words is called 2. out_file: the name of an output file that repeat_words creates Assume that the input file is in the current working directory and write the output file to that directory. For each line of the input file, the function repeat_words should write to the output file all of the words that appear more than...

  • 4)   Write a function named remove that returns void, takes in a string& called word, and...

    4)   Write a function named remove that returns void, takes in a string& called word, and an int called i that, starting from index 0, removes every ith letter from word by modifying it in place. Include a functional main method to make sure the program works. Programming language is C++, thanks in advance

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT