TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
大厅里有64盏灯,每盏灯都编了号码,分别为1-64。每盏灯都由一个开关来控制。(开关按一下,灯亮,再按一下灯灭。开关的编号与被控制的灯相同。)开始时,灯是全灭的。现在按照以下规则按动开关。
第一次,将所有的灯点亮。
第二次,将所有2的倍数的开关按一下。
第三次,将所有3的倍数的开关按一下。
以此类推。第N次,将所有N的倍数的开关按一下。
问第N次(N小于等于64)按完以后,大厅里还有几盏灯是亮的。
程序1: - public class Light{
- static long light=0;
- public static void main(String[] args) {
- int max=Integer.parseInt(args[0]);
- long start = System.currentTimeMillis() ;
- turnoff(max);
- //现在的light值,在某一位上如果取值为0表示灯灭,某一位上如果取值为1表示灯亮
- //下面输出结果
- int total = 0; //总共亮灯的数量
- for(int i=0; i<64; i++){
- long temp = 1;
- temp = temp << i;
- temp = temp & light;
- if(temp == 0){ //灯灭
- System.out.println("【"+(i+1)+"】号灯:灭");
- }else{ //灯亮
- System.out.println("【"+(i+1)+"】号灯:亮");
- total = total + 1;
- }
- }
- long end = System.currentTimeMillis() ;
- System.out.println("共消耗的时间:"+(end-start)+" 毫秒");
- System.out.println("在经过【"+max+"】次之后,总共有【"+total+"】盏灯是亮的!");
- }
- public static void turnoff(int n){
- for(int j=1; j<=n;j++){
- for(int i=1; i<=64 ; i++){
- //i代表了灯/开关的编号,需要将n的倍数所在的位取反
- //比如:n=1,那么,需要将1,2,3,4,5...这些位取反
- //n=2,需再将2,4,6,8,10...这些位取反
- //n=3,需再将3,6,9,12,15...这些位取反
- if(i % j == 0){
- //将i那一位取反
- //如何将某一位取反呢?没有直接将某一位取反的现成的操作,
- //那么,我们可以判断此位的值是1还是0,然后据此,将此位改成0或1
- //接下来的问题就是如何判断某位的值?如何将此为改成0或1?
-
- long temp = 1;
- temp = temp << (i - 1);
- if((temp & light) == 0){ //表示i这一位为0
- //需将此位改成1
- light = light | temp;
- }else{ //表示i这一位为1
- //需将此位改成0
- temp = ~temp;
- light = light & temp;
- }
- }
- }
- }
- }
-
-
- }
复制代码 程序(2)
- import java.util.*;
- public class TestLight{
-
- public static void main(String[] args) {
- int max=Integer.parseInt(args[0]);
- test(max);
- }
- public static void test(int n){
-
- long start = System.currentTimeMillis() ;
- List
-
- list = new ArrayList
-
- () ;
-
- for(int k=0;k<64;k++){
- list.add(0) ; //初始化都关着的 0表示关,1表示亮
- }
-
- for(int i=1;i<=n;i++){
- for(int j=1;j<=64;j++){
- if(j%i==0){
- list.set(j-1, ~(list.get(j-1))) ; //直接取反
- }
- }
- }
- int c =0 ;
- for(int s=0;s< list.size();s++){
-
- if(list.get(s).equals(0)){
- System.out.println("第"+ (s+1) +"盏灯关着的");
- }else{
- System.out.println("第"+ (s+1) +"盏灯开着的");
- c++ ;
- }
- }
- long end = System.currentTimeMillis() ;
- System.out.println("共消耗的时间:"+(end-start)+" 毫秒");
- System.out.println("共有:"+c+"亮着");
- }
- }
-
-
复制代码 运行:
C:java>java TestLight 64
第1盏灯开着的
第2盏灯关着的
第3盏灯关着的
第4盏灯开着的
第5盏灯关着的
第6盏灯关着的
第7盏灯关着的
第8盏灯关着的
第9盏灯开着的
第10盏灯关着的
第11盏灯关着的
第12盏灯关着的
第13盏灯关着的
第14盏灯关着的
第15盏灯关着的
第16盏灯开着的
第17盏灯关着的
第18盏灯关着的
第19盏灯关着的
第20盏灯关着的
第21盏灯关着的
第22盏灯关着的
第23盏灯关着的
第24盏灯关着的
第25盏灯开着的
第26盏灯关着的
第27盏灯关着的
第28盏灯关着的
第29盏灯关着的
第30盏灯关着的
第31盏灯关着的
第32盏灯关着的
第33盏灯关着的
第34盏灯关着的
第35盏灯关着的
第36盏灯开着的
第37盏灯关着的
第38盏灯关着的
第39盏灯关着的
第40盏灯关着的
第41盏灯关着的
第42盏灯关着的
第43盏灯关着的
第44盏灯关着的
第45盏灯关着的
第46盏灯关着的
第47盏灯关着的
第48盏灯关着的
第49盏灯开着的
第50盏灯关着的
第51盏灯关着的
第52盏灯关着的
第53盏灯关着的
第54盏灯关着的
第55盏灯关着的
第56盏灯关着的
第57盏灯关着的
第58盏灯关着的
第59盏灯关着的
第60盏灯关着的
第61盏灯关着的
第62盏灯关着的
第63盏灯关着的
第64盏灯开着的
共消耗的时间:171 毫秒
共有:8亮着
源码下载:http://file.javaxxz.com/2014/12/3/000711000.zip |
|