Header Ad

Leetcode Bulb Switcher problem solution

In this Leetcode Bulb Switcher problem solution, There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. In 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. Return the number of bulbs that are on after n rounds.

Leetcode Bulb Switcher problem solution

Problem solution in Python.

class Solution:
    def bulbSwitch(self, n: int) -> int:
        return int(n**0.5)

Problem solution in Java.

public int bulbSwitch(int n) {
        List arr = new ArrayList<>();
        for(int i = 1; i * i <= n; i++){
        return arr.size();

Problem solution in C++.

class Solution {
    int bulbSwitch(int n) {
        long long lo = 0, hi = 100000000;
        while(lo <= hi){
            long long mid = (lo + hi) / 2;
            if(mid * mid == n)return mid;
            if(mid * mid <= n){
                lo = mid + 1;
                hi = mid - 1;
        return hi;

Problem solution in C.

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

Post a Comment