[Leetcode]Bulb Switcher

来源:互联网 发布:即时消息软件 编辑:程序博客网 时间:2024/05/16 01:39
  1. Bulb Switcher
    Total Accepted: 970 Total Submissions: 2597 Difficulty: Medium

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.

Subscribe to see which companies asked this question

应该是今天新出的题目,如果这个灯泡可以被开关偶数次,那么它最后就是灭的;如果被开关奇数次,那么它最后就是亮的。

那么什么位置上的灯泡可以被开关奇数次呢?
考虑一个非平方数,如15,它的约数是1,3,5,15。发现没,它的约数是对称存在的!这个时候它最后只会被开关偶数次!但是对于一个平方数,如16,它的约数是1,2,4,8,16。也只有这样的平方数才能最后被开关奇数次!

所以我们的目的就是找出n以内有几个完全平方数。这一点就没什么问题了,直接开平方就行!

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