319. Bulb Switcher

319. Bulb Switcher

Bulb Switcher

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.

Example 1:

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.

题目地址:Bulb Switcher

题意:
给定n,共有n盏灯,初始的时候灯都是灭的,然后进行n轮开关灯,规则是第i轮内要将i的倍数的灯都反转。求最后灯打开的个数。

思路:
对于第j轮的第 i 盏灯,只有当j i 的因子时才会对它进行开关操作,也就是说在n轮中对第 i <script type="math/tex" id="MathJax-Element-5">i</script>盏灯开关操作的次数等于其因子的个数。

初始的时候灯都是灭的,所以当i有偶数个因子时,最后第i盏灯就是灭的,反之则是打开的。

对于素数,因子必然为两个(1和自身)。回忆下求某数因子个数的算法:

for(int i = sqrt(n);i > 0;--i){
    if(n%i == 0){
        if(i*i == n) ans++;
        else ans += 2;
    }
}

就是说只有当某数是平方数时,因子个数才为奇数,灯最后才是打开的。答案等于[0,n]内平方数的个数floor(sqrt(n))。

C++

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

C++知识点

隐式类型转换:
当调用函数时,函数返回值和形参会发生隐式的强制类型转换。

经验:
当没有思路时,找几个简单的数据模拟,观察输入、输出值的规律,往往有助于找到新的解题思路。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值