Wednesday, 28 December 2016

Smallest Integer multiplication to floating number which convert it to natural

We need to find the Integer Multiplier to convert a floating number to Natural.

Input : 1.66
Output : 50

Input : 0.25
Output : 4

public class MinMulToMakeNatural {

     /**
      * Get Minimum multiplier to make Natural.
      * @param number
      * @return min mult.
      */
     private static int getMinMultiplier(float number) {
           char[] array = (number+"").toCharArray();
          
           int len = array.length;
           int numerator = array[0]- '0';
           int count = 0;
          
           boolean flag = false;
           for (inti = 1 ; i <= len-1; i++) {
                if('.'==array[i]) {
                     flag= true;
                     continue;
                }
               
                if(flag) {
                     count++;
                }
               
                int val = array[i] - '0';
                numerator = numerator * 10 + val;
           }
          
           int denominator = (int)Math.pow(10,count);
          
           int gcd = getGCD(numerator,denominator);
          
           return denominator/gcd;
     }   
    
     /**
      * @param numerator
      * @param denominator
      * @return GCD
      */
     private static int getGCD(int numerator, intdenominator) {
          
           int gcd = denominator==0?numerator:
                getGCD(denominator, numerator%denominator);
          
           return gcd;
     }

     /** Main method. */
     public static void main(String[] args) {
           float number = 1.66F;
          
           int min = getMinMultiplier(number);
          
           System.out.println("Minimum Integer Multiplier# "+min);
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...