Bulb Switcher in C++

C++Server Side ProgrammingProgramming

Suppose there are n bulbs that are initially switched off. We first turn on all the bulbs. Then, we turn off every second bulb. On the third round, we toggle every third bulb (turning on if it's off or turning off if it's on). Similarly, for the i-th round, we toggle every i bulb. For the n-th round, we only toggle the last bulb. So we have to find how many bulbs are on after n rounds. So if the input is 3, then the result will be 1. This is because −

  • 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].

To solve this, we will follow these steps −

  • This step is straight forward, we have to find the square root of n and return.

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int bulbSwitch(int n) {
      return sqrt(n);
   Solution ob;
   cout << (ob.bulbSwitch(3));




Updated on 02-May-2020 12:43:29