File tree Expand file tree Collapse file tree
main/java/com/github/mstepan/leetcode/medium
test/java/com/github/mstepan/leetcode/medium Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments