Division with cycle remainder

By | December 16, 2014
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Divide number and return result in form of a string. e.g 100/3 result should be 33.(3) Here 3 is in brackets because it gets repeated continuously and 5/10 should be 0.5.

The essence is to use hashmap to restore the remainder. Once a certain remainder was obtained for 2nd time, we found the recycles.

  1. public class DivisionWithCycleRemainder {
  2.     public static void main(String[] args){
  3.         String result = divisionToString(45,17);
  4.         System.out.println(result);
  5.     }
  6.     public static String divisionToString(int num1, int num2) {
  7.         int beforeD = num1 / num2;    //the result before dot
  8.         int afterD = num1 % num2;    //the result after dot
  9.         if(afterD==0){
  10.             return String.valueOf(beforeD);
  11.         }
  12.         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
  13.         StringBuffer result = new StringBuffer(beforeD + “.”);
  14.         int remainder = afterD * 10;
  15.         while(!hm.containsKey(remainder)){
  16.             hm.put(remainder, result.length());    //remainder never exist, insert into hm
  17.             int curr_value = remainder / num2;    //result of current position
  18.             result.append(curr_value);
  19.             remainder = (remainder % num2) * 10;
  20.         }
  21.         result.insert(hm.get(remainder).intValue(), ‘(‘);
  22.         result.append(‘)’);
  23.         return result.toString();
  24.     }
  25. }