Leetcode 319. Bulb Switcher

这是一个非常巧妙的题目,网站称之为brain teaser,意思就是代码写起来会非常简介(就是逗你玩:)),题目如下:

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 nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Example:

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.

第一次: 1×1 只有这一种情况,所以所有的灯泡由off --> on
第二次:2×1 1*2也就是说会有两个switch,一个是1为间隔的switch,一个是2为间隔的switch,off->on-->off
第三次:如前面所示,1×3 3×1,off-->on-->off
,,,,,

以此类推,我们发现a*b总是有b*a相对应,也就是说,有偶数个switch,这样的话,off还是off,on还是on,也就是保持不变,除了一种情况,就是3×3这种,如果sqrt(间隔)为整数,则表示有奇数次switch,会发生状态的变化,那么我们现在再考虑这个问题就很简单了,因为一开始所有的灯泡都是灭的,所以我们只需要寻找满足1.小于n,2.且sqrt为整数的个数。答案显然是sqrt(n)

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

转载于:https://www.cnblogs.com/RookieCoder/p/5071483.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值