Topic: 分硬币问题(用递归方法!!!) |
Print this page |
1.分硬币问题(用递归方法!!!) | Copy to clipboard |
Posted by: xingchao Posted on: 2008-02-12 00:59 开发一个递归方法,确定将一定数量的钱(以美分为单位)转换成两角五分的硬币,一角硬币,五分和一分硬币的方法总数。例如,假设总钱数为17分,那么共有6种方法。 1角,7分 1角,1五分,2一分 3五分,2一分 2五分,7一分 1五分,12一分 17一分 为方便起见,可以理解为用25,10,5,1分解一个数,求一共有多少种分解方法?? 要用递归方法啊! 最好能给出个源代码,或者给些提示也可以,谢谢。 |
2.Re:分硬币问题(用递归方法!!!) [Re: xingchao] | Copy to clipboard |
Posted by: suntao19830709 Posted on: 2008-03-05 16:16
|
3.Re:分硬币问题(用递归方法!!!) [Re: xingchao] | Copy to clipboard |
Posted by: suntao19830709 Posted on: 2008-03-05 16:22 楼上是我的算法,核心代码就
注释写的不多,不知道你能否看明白。另外,我的解法里17可以任意改成别的数,用来分的钱币,也可以通过修改上面的数组来实现 |
4.Re:分硬币问题(用递归方法!!!) [Re: xingchao] | Copy to clipboard |
Posted by: istimeto Posted on: 2008-06-05 22:49 楼上功底很深,呵呵! 不过我觉得,这个二重循环,完全可以避免的。只需要把参数 public int divider(int num, int dividerNum)中的dividerNum,改为当前可用的最大额的硬币所对应数组divider[] = new int[]{1, 5, 10, 25}的下标,当然前提是该数组要有序的,这样我看起来直观。 |
5.Re:分硬币问题(用递归方法!!!) [Re: xingchao] | Copy to clipboard |
Posted by: jancyu2008 Posted on: 2008-06-28 00:32 Very good |
6.Re:分硬币问题(用递归方法!!!) [Re: istimeto] | Copy to clipboard |
Posted by: suntao19830709 Posted on: 2008-07-08 15:30 istimeto wrote: 呵呵,你说的极是,当时匆忙了点,没注意。 改成下标确实不用循环了,只要,数组是有序的。 上面的代码其实还有地方没考虑,就是如果切分的硬币没有1分的,会出现这样的问题:最终的余数为1分,但没有1分硬币来作为这个分配的结果,这样,分配的结果就只能取消,不能算数了。 |
7.Re:分硬币问题(用递归方法!!!) [Re: xingchao] | Copy to clipboard |
Posted by: istimeto Posted on: 2008-07-08 18:39 呵呵,对,严谨!! 前提要是可拆分的。否则就要差错检测和处理。 |
8.Re:分硬币问题(用递归方法!!!) [Re: xingchao] | Copy to clipboard |
Posted by: Miragi_Song Posted on: 2008-07-12 02:44 is using loop necessary here..... this is my algorithm which might be a little verbose but simple to comprehend- - here I use the Standard object //cent is the variable which stores the amount of coins that are waiting to be exchanged import hsa.*; int cent, quarter,dime, nickel; Stdout.println("Type in the amount of the total coins:"); cent=Stdin.readInt(); //use integer division to get the integer part and make the "cent" variable overwritten by the remainder part. quarter=cent/25; cent=cent%25; dime=cent/10; cent=cent%10; nickel=cent/5; cent=cent%5; Stdout.println("These coins can be exchanged into: " + quarter+" quarter( s ) "+dime+" dime( s ) "+nickel+" nickel( s ) "+cent+" pennie( s ).") |
9.Re:分硬币问题(用递归方法!!!) [Re: xingchao] | Copy to clipboard |
Posted by: JiafanZhou Posted on: 2008-07-15 16:17 I see couple of implementations here regarding to deal with this particular issue. So far I have to say suntao19830709's algorithm is the best and very clear to understand. |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |