
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Bulb Switcher Problem in C++
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 −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int bulbSwitch(int n) { return sqrt(n); } }; main(){ Solution ob; cout << (ob.bulbSwitch(3)); }
Input
3
Output
1
Advertisements