Question -
Implement a Cash Register given a bill and amount paid by the customer return the amount of change which has to be provided to the customer.
For Example -
Bill - 100.00
Output - FIFTY DOLLAR,DOLLAR,HALF DOLLAR
Condition
If Bill == amount return "ZERO"
if BILL > amount return "ERROR"
You have to take input from the console and it should run until an input is being given by the user.
Input format - Bill;Amount paid
For Example - 48.50;100.0
My JAVA implementation -
(Why TreeMap instead of HashMap? TreeMap by default stores the keys in a sorted manner, unlike HashMap which stores it randomly)
public static String calculateChange(Double amt, Double bill){
if(Objects.equals(bill, amt)) return "ZERO";
if(amt > bill) return "ERROR";
Double diff = bill - amt;
Map<Double,String> map = new TreeMap<>(Collections.reverseOrder());
map.put(100.0, "HUNDRED DOLLAR");
map.put(50.0, "FIFTY DOLLAR");
map.put(20.0, "TWENTY DOLLAR");
map.put(10.0, "TEN DOLLAR");
map.put(5.0, "FIVE DOLLAR");
map.put(2.0, "TWO DOLLAR");
map.put(1.0, "DOLLAR");
map.put(0.5, "HALF DOLLAR");
map.put(0.25, "QUARTER");
map.put(0.1, "DIME");
map.put(0.05, "FIVE CENT");
map.put(0.02, "TWO CENT");
map.put(0.01, "CENT");
StringBuffer sb = new StringBuffer();
for(Double curr : map.keySet()){
if(curr <= diff){
while(curr <= diff) {
if (sb.length() > 1) sb.append(",");
sb.append(map.get(curr));
diff -= curr;
}
}
}
return sb.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
String st = sc.nextLine();
Double amt = Double.valueOf(st.split(";")[0]);
Double bill = Double.valueOf(st.split(";")[1]);
System.out.println(calculateChange(amt,bill));
}
}Key Learnings from this OA ?
I was under the impression that I dont have to handle the input (as we have in LeetCode, where we get everything in our function and we simply return the result), so when I saw the question I was confused and did not know how to go about it, I was able to complete the code in 15 - 20 minutes, but I could not figure out how to go about that input part, in such short time I was unable to figure out the input part, so I was unable to run my code over there.