Bulb Switcher II in C++


Suppose there is a room with n lights which are switched on initially and 4 buttons present on the wall. After performing exactly m unknown operations towards buttons, we need to return how many different kinds of status of the n lights could be. So consider n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are as follows −

  • Flip all the lights.
  • Flip lights with even numbers.
  • Flip lights with odd numbers.
  • Flip lights with (3k + 1) numbers, k = 0, 1, 2, ...

Now if n = 3 and m = 1, then there will be 4 operations, these are, [off, on, off], [on, off, on], [off, off, off], [off, on, on]

To solve this, we will follow these steps −

  • if n is 0 or m is 0, then return 1
  • if n is 1, then return 2
  • if n is 2, then return 3, when m is 1, otherwise return 4
  • if m is 1, then return 4
  • if m is 2, then return 7, otherwise return 8.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int flipLights(int n, int m) {
      if (m == 0 || n == 0) return 1;
      if (n == 1) return 2;
      if (n == 2) return m == 1? 3:4;
      if (m == 1) return 4;
      return m == 2? 7:8;
   }
};
main(){
   Solution ob;
   cout << (ob.flipLights(3, 1));
}

Input

3
1

Output

4

Updated on: 04-May-2020

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements