LeetCode 319. Bulb Switcher 题解(C++)

来源:互联网 发布:php获取qq信息 编辑:程序博客网 时间:2024/06/06 02:33

LeetCode 319. Bulb Switcher 题解(C++)


题目描述

  • There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it’s off or turning off if it’s on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

举例

  • Given n = 3.

    At first, the three bulbs are [off, off, off].
    After first round, the three bulbs are [on, on, on].
    After second round, the three bulbs are [on, off, on].
    After third round, the three bulbs are [on, off, off].

    So you should return 1, because there is only one bulb is on.

思路

  • 这道题只要一行代码就可以解决,首先,假设现在有第i盏灯,初始是off的,假设从1到i的每个整数,可以被i整除的个数为k(能被i整除即说明该趟可以打开或者关闭第i盏灯),则我们需要知道若k为奇数,则灯被切换了奇数次,则此时灯的状态是on;若k为偶数,则灯被切换了偶数次,此时灯的状态仍然是off;
  • 下一步,我们需要知道,i的因子是成对出现的,即若第t趟的t能被i整除,则还存在另外一个数i/t能被i整除(即第i/t趟),若两个因子不同,则两次切换之后灯的状态还是原来的状态,若两个因子相同,则两次切换之后灯的状态与原来的状态相反(因为因子相同只需切换一次),两个因子相同即代表该因子为i的平方根;
  • 从上面分析可知,我们只需知道第i盏灯的i是否能由两个相同的整数相乘得到(即开平方根),若可以,则第i盏灯切换了奇数次,灯的状态与初始状态off相反,为on;若不可以,则切换了偶数次,灯的状态与初始状态on相同,仍为on;
  • 于是我们只需要计算从1~n中可以开平方的数的数量即可,这里只需直接求n的平方根,就是1~n中可以开平方的数的数量。

代码

class Solution{public:    int bulbSwitch(int n)     {        return sqrt(n);    }};
0 0