Search code examples
javaeclipseintegerdoublealgebraic-data-types

Transformation of two integers into a double in Java


This is the task:

Implement a static-public method named "createDouble" in the class "Functionality.java". The method gets two integer values a and b as input and should transform them to a double value and return it as follows:

  • The first input value a, should be placed before the comma or dot.
  • The second input value b, should be after the comma or dot and superfluous zeros should be removed.

No imports may be used to solve this task. Also the use of the Math library or other libraries is prohibited. Implement an algorithm that contains at least one meaningful loop.

This was my idea:

public class Functionality {

    public static double createDouble(int a, int b) {
        double c = b;
        double d = 1;
        while (c >= 1) {
            c /= 10;
            d *= 10;
        }
        return a + b/d;
    }

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(createDouble(12, Integer.MAX_VALUE));
    }
}

The problem is I am using the Method Integer.MAX Value which I shouldn´t use. Is there another option to write this code ?


Solution

  • Your code looks sound, just a small tweek I would make. Your variable c will equal what you want b to be after it's done dividing so you can just use it directly. Otherwise, you don't really need to be using Integer.MAX_VALUE at all. Just use arbitrary values.

    public class Functionality
    {
      public static double createDouble(int a, int b) {
        double c = b;
        while(c >= 1)
          c /= 10;
        return a + c;
      }
      
      public static void main(String[] args) {
        System.out.println(createDouble(15, 351));
        System.out.println(createDouble(32, 8452));
      }
    }
    

    Output:

    15.351
    32.8452