Created
August 11, 2014 14:00
-
-
Save WOLOHAHA/caa08a3b3f833693ca9d to your computer and use it in GitHub Desktop.
Given an infinite number of quarters(25 cents), dimes(10 cents), nickels(5 cents) and pennies(1 cent), write code to calculate the number of ways of representing n cents.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package POJ; | |
public class Main { | |
/** | |
* | |
* 9.8 Given an infinite number of quarters(25 cents), dimes(10 cents), nickels(5 cents) and pennies(1 cent), | |
* write code to calculate the number of ways of representing n cents. | |
* | |
* | |
*/ | |
public static void main(String[] args) { | |
Main so = new Main(); | |
System.out.println(so.makeChange(10, 25)); | |
} | |
public int makeChange(int n, int denom) { | |
int next_denom = 0; | |
switch (denom) { | |
case 25: | |
next_denom = 10; | |
break; | |
case 10: | |
next_denom = 5; | |
break; | |
case 5: | |
next_denom = 1; | |
break; | |
case 1: | |
return 1; | |
} | |
int ways = 0; | |
for (int i = 0; i * denom <= n; i++) { | |
ways += makeChange(n - i * denom, next_denom); | |
} | |
return ways; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment