如下是在网上看到的一道题目:java
大厅里有100盏灯,每盏灯都编了号码,分别为1-100。每盏灯由一个开关来控制。(开关按一下,灯亮,再按一下灯灭。开关的编号与被控制的灯相同。)开始时,灯是全灭的。如今按照如下规则按动开关。
第一次,将全部的灯点亮。
第二次,将全部2的倍数的开关按一下。
第三次,将全部3的倍数的开关按一下。
以此类推。第N次,将全部N的倍数的开关按一下。
问第N次(N大于等于2,且小于等于100)按完之后,大厅里还有几盏灯是亮的。编程
请编程实现上面的逻辑,以N为参数数组
个人思路以下:code
1,灯的状态变化是什么。灯的开关只有俩种状态,非开即关。因此用一个变量定义一下开关状态,我用数组的值A或B来定义灯的开关,其实我以为用一个布尔值会更好。get
if(i%n==0){ if(lamp[i]=="A"){ lamp[i]="B"; }else { lamp[i]="A"; } }
2,灯的状态如何变。第一次,全变。第二次,2的倍数变一次。第三次,3的倍数变一次。以此类推能够得出:每一次,但凡是次数整数倍的都会变。因此我用取余为0来判断是否进行变换。那么,它的开关次数的逐次递增用一个for循环来解决。input
for(int n=1;n<N+1;n++){ for(int i=0;i<100;i++){ //the change of "A"and"B"means:lamp is open or close if(i%n==0){ if(lamp[i]=="A"){ lamp[i]="B"; }else { lamp[i]="A"; } } } }
3,在灯的变化结果已经出来时,就是统计最后开着的灯的数量。用判断,累计。it
(PS:对于count有定义却没有初始化值,致使一直出错却找不到缘由,通常来讲定义都有默认初始化的值,可是总有不肯定隐患发生,因此仍是要谨慎***)io
for(int i=0;i<100;i++){ System.out.print(lamp[i]); if(lamp[i]=="A"){ //output the number of lamp how many is open count=count+1; } } System.out.println(); System.out.print("the number of open lamp is:"+count);
所有代码显示以下:for循环
import java.util.Scanner; class Demo12{ public static void main(String[] args){ change(); } public static void change(){ //I have forget to initialize the value count,that make a false and I spend half an hour to find it. int count=0; int N; String[] lamp={"B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B"}; //define the volue of N as the number of times System.out.println("please input an number:"); Scanner key=new Scanner(System.in); N=key.nextInt(); for(int n=1;n<N+1;n++){ for(int i=0;i<100;i++){ //the change of "A"and"B"means:lamp is open or close if(i%n==0){ if(lamp[i]=="A"){ lamp[i]="B"; }else { lamp[i]="A"; } } } } //output the situation of lamp for(int i=0;i<100;i++){ System.out.print(lamp[i]); if(lamp[i]=="A"){ //output the number of lamp how many is open count=count+1; } } System.out.println(); System.out.print("the number of open lamp is:"+count); } }