1 line C++ code with explanation


  • 2
    N

    Only lights labeled as perfect squares will be on because perfect squares have odd numbers of divisors.

    1st bulb (1: 1): 1 on ------- 1=1^2

    2nd bulb (2: 1,2): 1 on, 2 off

    3rd bulb (3: 1,3): 1 on, 3 off

    4th bulb (4: 1,2,4): 1 on, 2 off, 4 on ------ 4=2^2

    5th bulb (5: 1,5): 1 on, 5 off

    6th bulb (6: 1,2,3,6): 1 on, 2 off, 3 on, 6 off

    7th bulb (7: 1,7): 1 on, 7 off

    8th bulb (8: 1,2,4,8): 1 on, 2 off, 4 on, 8 off

    9th bulb (9: 1,3,9): 1 on, 3 off, 9 on --------- 9=3^2

    and so on...

    int bulbSwitch(int n) {
        return sqrt(n);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.