您的位置:首页 > 其它

leetcode刷题,总结,记录,备忘 319

2015-12-28 20:39 381 查看
leetcode319, 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 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

一开始并没有弄懂题目的意思,还使用位运算之类,搞了半天,提交了十几次都没成功,无奈去咨询别人的博客,自己又思考了良久,才弄懂这题,题目的意思是第一轮全亮,第二轮每逢第二个灭掉,第三轮每逢第三个反转,之后第n轮就反转第n个灯的状态。仔细一想,就可以得知,第几个灯一共被操作几次,就可以得到其最后的结果,如果是第质数个的灯的话,比如1,3,5,7,11,在整个过程中只会被操作两次,即第一次和第n次,所以最后的状态一定是灭的。从此可以看出第n个灯的操作次数是他们的的因数的个数,比如6,因数为1,2,3,6,一共操作了四次,最后结果是灭的,所以只有奇数的操作次数的灯最后才会亮,比如第4个灯,因数为1,2,4,因为存在是2的平方的原因,因数少了一个,这样的灯在最后是会亮着的,所以这道题目,就是求<=n的数中,有多少个完全平方数,代码就很简单了。
class Solution {
public:
int bulbSwitch(int n) {
return (int)sqrt(n);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: