319. 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:

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

 

复制代码
class Solution(object):
    def bulbSwitch(self, n):
        """
        :type n: int
        :rtype: int
n=8
0,00000000
1,11111111
2,10101010
3,10001110
4,10011111
5,10010111
6,10010001
7,10010001
8,10010000=>2
bit 1=>1
bit 2=>0
bit 3=>0
bit 4=>1,2,4=>1
bit 5=>1,5=>0
bit 6=>1,2,3,6=>0
bit 7=>1,7=>0
bit 8=>1,2,4,8=>0
bit 9=>1,3,9=>1
bit 10=>1,2,5,10=>0
bit 11=>1,11=>0
bit 12=>1,2,3,4,6,12=>0
bit 13=>1,13=>0
bit 14=>1,2,7,14=>0
bit 15=>1,3,5,15=>0
bit 16=>1,2,4,8,16=>1 

only if bit n is a square number
        """
        ans = 0
        i = 1
        while i*i <= n:
            i += 1
            ans += 1
        return ans        
复制代码

 

posted @   bonelee  阅读(243)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示