?????????????????????????????????? 一道很簡單的老問題,求更好的解決方法
??????????????????????????????????????????? 馬嘉楠?? 2006-11-08
今天在一個論壇看到有人問一個很老的問題。
“10個人圍一圈,編號為1的人開始數(shù)數(shù),數(shù)到能被3整除的編號的人退出,然后再往下數(shù)。問最后剩幾個人?
如第一圈后:3,6,9退出,還剩7人下一圈從第11開始數(shù)。求算法”
看到過這個題目很多次,從來都沒有仔細想過寫過代碼。
下面的方法是我今天看到題目后的第一反應(yīng),應(yīng)該有更好的吧。
你們都是怎么做的啊,學習一下,謝謝啦!
我算法很弱的。。。
一、數(shù)組實現(xiàn)
1.??? for循環(huán)初始化每個人的值為0
2.??? 開始報數(shù),如果所報之數(shù)能被3整除,設(shè)置此人的值為1
3.??? 如此循環(huán)下去,直到只有一個人的值為0
4.??? 獲得此人在數(shù)組中的下標,加1之后輸出,即為所求
package
?Test;
public
?
class
?Main?{
????
public
?
static
?
void
?main(String[]?args)?{
????????
int
[]?person?
=
?
new
?
int
[
10
];
????????
for
?(
int
?i?
=
?
0
;?i?
<
?person.length;?i
++
)?{
????????????person[i]?
=
?
0
;
????????}
????????
for
?(
int
?j?
=
?
0
,?count?
=
?
0
,?leave?
=
?person.length;?leave?
!=
?
1
;?j?
=
?(j?
+
?
1
)
%
(person.length))?{
????????????
if
?(person[j]?
==
?
1
)?{
????????????????
continue
;
????????????}?
else
?{
????????????????count
++
;
????????????????
if
?(count?
%
?
3
?
==
?
0
)?{
????????????????????person[j]?
=
?
1
;
????????????????????leave
--
;
????????????????}
????????????}
????????}
????????
for
?(
int
?i?
=
?
0
;?i?
<
?person.length;?i
++
)?{
????????????
if
?(person[i]?
==
?
0
)?{
????????????????System.out.println(
"
The?last?person?is?
"
?
+
?(i?
+
?
1
));
????????????????
return
;
????????????}
????????}
????}
}
馬嘉楠
jianan.ma@gmail.com
posted on 2006-11-08 18:05
馬嘉楠 閱讀(415)
評論(0) 編輯 收藏 所屬分類:
SoureCode