package com.hanqi.count;
// 逢三退一 輸出留到最后值的索引;
public class Count1 {
//主方法
public static void main(String[] args) {
Count1 c = new Count1();
System.out.println(c.count(6));
// 方法有返回值 , 傳入數組長度(總共多少數);
}
// 逢3 退1;
public int count (int in) {
//聲明一個boolean數組
boolean arr[] = new boolean[in];
for (int i = 0; i < arr.length; i++) {
arr[i] = true;
//把數組的值替換為 ture;
}
int count = arr.length ; //總計數(獲取數組長度)
int threecount = 0; // 3次循環計數
int index =0; //當前數組的序號
while (count > 1) {
//只要還有 1個以上的值為true 就會一直運行
if(arr[ index ]) {
threecount ++; // 值為treu 時+1
if(threecount == 3) {
arr[index] = false;
threecount = 0;
count --; //進一遍總數減1 因為逢3去1 ;
}
}
index ++; // 放在 if判斷上面 arr.length 長度為500 但是序號是從0開始所以到499結束;
if (index == arr.length) {
index = 0;
}
//index ++; 放在 if判斷底下歸零后立馬加1 所以不行(邏輯問題);
}
int ret = 0;
// 遍歷 留到最后為true的值得索引
for (int i = 0; i < arr.length; i++) {
if (arr[i]) {
// 值為true時輸出i ,此時i為最后一個值的序號;
//System.out.println(i);
ret = i;
break;
}
}
return ret;
}
}
這道題提醒了我 換個思路看看;(用boolean數組解決問題)
