Skip to content

Commit da3cc21

Browse files
author
Maksym Stepanenko
committed
319. Bulb Switcher solved for fun.
1 parent 0840654 commit da3cc21

2 files changed

Lines changed: 92 additions & 0 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.github.mstepan.leetcode.medium;
2+
3+
/**
4+
* 319. Bulb Switcher
5+
*
6+
* <p>https://leetcode.com/problems/bulb-switcher/description/
7+
*/
8+
public class BulbSwitcher {
9+
10+
/**
11+
* time: O(sqrt(N))
12+
*
13+
* <p>space: O(1)
14+
*/
15+
public static int bulbSwitch(int n) {
16+
17+
if (n < 0) {
18+
throw new IllegalArgumentException("Can't handle negative value");
19+
}
20+
21+
if (n < 2) {
22+
return n;
23+
}
24+
25+
int leftSize = n;
26+
int bitsSetCnt = 0;
27+
28+
for (int zerosCnt = 2; leftSize > 0; zerosCnt += 2) {
29+
leftSize = leftSize - 1 - zerosCnt;
30+
++bitsSetCnt;
31+
}
32+
33+
return bitsSetCnt;
34+
}
35+
36+
// public static void main(String[] args) {
37+
// for (int i = 0; i <= 100; ++i) {
38+
// System.out.printf("{%d}: %s%n", i, bulbSwitchString(i));
39+
// }
40+
// }
41+
//
42+
// private static String bulbSwitchString(int n) {
43+
// if (n == 0) {
44+
// return "";
45+
// }
46+
//
47+
// if (n == 1) {
48+
// return "1";
49+
// }
50+
//
51+
// final boolean[] result = new boolean[n];
52+
// Arrays.fill(result, true);
53+
//
54+
// for (int offset = 2; offset <= n; ++offset) {
55+
// for (int idx = offset - 1; idx < result.length; idx += offset) {
56+
// result[idx] = !result[idx];
57+
// }
58+
// }
59+
//
60+
// StringBuilder resultAsStr = new StringBuilder(n);
61+
//
62+
// for (boolean bit : result) {
63+
// resultAsStr.append(bit ? "1" : "0");
64+
// }
65+
//
66+
// return resultAsStr.toString();
67+
// }
68+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.github.mstepan.leetcode.medium;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
public class BulbSwitcherTest {
9+
10+
@Test
11+
void bulbSwitch() {
12+
assertEquals(0, BulbSwitcher.bulbSwitch(0));
13+
assertEquals(1, BulbSwitcher.bulbSwitch(1));
14+
assertEquals(1, BulbSwitcher.bulbSwitch(2));
15+
assertEquals(4, BulbSwitcher.bulbSwitch(16));
16+
}
17+
18+
@Test
19+
void bulbSwitchNegativeValueThrowsException() {
20+
assertThrows(IllegalArgumentException.class, () -> BulbSwitcher.bulbSwitch(-1));
21+
assertThrows(IllegalArgumentException.class, () -> BulbSwitcher.bulbSwitch(-5));
22+
assertThrows(IllegalArgumentException.class, () -> BulbSwitcher.bulbSwitch(-133));
23+
}
24+
}

0 commit comments

Comments
 (0)