Java program to solve Smallest Number Of Coins problem.
Program Using Doubles
import java.util.Scanner; // 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Main { public static void main(String[] args) { double moneyValues[] = { 500, 200, 100, 50, 20, 10, 5, 2, 1, 0.50, 0.25, 0.1, 0.05, 0.01 }; Scanner scanner = new Scanner(System.in); System.out.print("Enter money amount: "); double moneyAmount = scanner.nextDouble(); System.out.println("Money values:"); int currentMoneyValue = 0; int moneyValueCount = 0; while(moneyAmount > moneyValues[moneyValues.length - 1]){ if(moneyAmount < moneyValues[currentMoneyValue]){ ++currentMoneyValue; }else{ moneyAmount -= moneyValues[currentMoneyValue]; System.out.print(moneyValues[currentMoneyValue] + " "); ++moneyValueCount; } } System.out.println(""); System.out.println("Total money values needed: " + moneyValueCount); } }
Note that this program can generate bad results due to double rounding errors. To encounter that try it with “11.11”. If you want to fix it just use program bellow.
Program Using BigDecimals
import java.math.BigDecimal; import java.util.Scanner; // 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Main { public static void main(String[] args) { double moneyValues[] = { 500, 200, 100, 50, 20, 10, 5, 2, 1, 0.50, 0.25, 0.1, 0.05, 0.01 }; Scanner scanner = new Scanner(System.in); System.out.print("Enter money amount: "); BigDecimal money = BigDecimal.valueOf(scanner.nextDouble()); System.out.println("Money values:"); int currentMoneyValue = 0; int moneyValueCount = 0; while(money.compareTo(BigDecimal.valueOf(moneyValues[moneyValues.length - 1])) >= 0){ if(money.compareTo(BigDecimal.valueOf(moneyValues[currentMoneyValue])) < 0){ ++currentMoneyValue; }else{ money = money.subtract(BigDecimal.valueOf(moneyValues[currentMoneyValue])); System.out.print(moneyValues[currentMoneyValue] + " "); ++moneyValueCount; } } System.out.println(""); System.out.println("Total money values needed: " + moneyValueCount); } }
Sample Output:
Enter money amount: 254.78 Money values: 200.0 50.0 2.0 2.0 0.5 0.25 0.01 0.01 0.01 Total money values needed: 9