To see a very interesting programming problem: the hall, there are 64 lamps, each lamp is compiled numbers 1-64, respectively. Each lamp controlled by a switch. (Switch click, lights, and then click the lights turned off. Switch number and be controlled the same light.) Began when the lamp is Quanmie's. In accordance with the following rules are now pressed switches. The first time, all the lights lit. The second time, all the multiples of 2, the switch click. The third time, all the multiples of 3, the switch click. And so on. The first N times, all the multiples of N, the switch click. Question No. N times (N less than or equal 64) by End after the hall there is Jizhan Deng was lit. Tip can use long digital to do, very clever just fine, said a 64-bit, 0 or 1 on behalf of open or close down. Implementation and the original author wrote a basic idea is the same:

/** * * @author: yanxuxin * @date: 2010-3-13 */ public class LightSwiter { public static void main(String[] args) { long lights = switchLights(3); convert2Binary(lights); System.out.println(); countOpenedLights(lights); } /** * Toggle switch * * @param sequence * @return */ public static long switchLights(int sequence) { long lights = 0l; // All are closed status, i.e. 64 Bits are 0 for (int i = 1; i <= sequence; i++) { for (int j = 1; j <= 64; j++) { if (j % i == 0) { // Subject to the n number of times a multiple of long temp = 1l; temp = temp << (j - 1); // Ready to intercept the current bits if ((lights & temp) == 0) { // Indicates that the current bits lights 0, That is, closed lights = lights | temp; // Does not affect other digits to the left, change lights The current position of the State is 1 } else { temp = ~temp; lights = lights & temp; // Does not affect other digits to the left, change lights The current position of the State is 0 } } } } return lights; } /** * Statistics on the number of lights * * @param lights */ public static void countOpenedLights(long lights) { int remains = 0; for (int k = 0; k < 64; k++) { long temp = 1l; temp = temp << k; temp = (lights & temp); // Interception of current bit judgment if (temp != 0) { remains++; System.out.println("The " + (k + 1) + " light is opened."); } } System.out.println("Total " + remains + " lights are opened."); } /** * Translated into binary expressions show * * @param number */ public static void convert2Binary(long number) { long res = number / 2; long rem = number % 2; if (res != 0) { convert2Binary(res); } System.out.print(rem); } }

Topic answer trick is that the use of bit operations to transform the status of each one, very good idea.