-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconcatenation_of_consecutive_binary_numbers.dart
120 lines (95 loc) · 2.61 KB
/
concatenation_of_consecutive_binary_numbers.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
- Concatenation of Consecutive Binary Numbers *-
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.
Example 1:
Input: n = 1
Output: 1
Explanation: "1" in binary corresponds to the decimal value 1.
Example 2:
Input: n = 3
Output: 27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.
Example 3:
Input: n = 12
Output: 505379714
Explanation: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
Constraints:
1 <= n <= 105
*/
// Disclaimer : -* Unfortunately this Solution is not available in DART on Leetcode *-
// Solution :- Check the Golang Version for leetcode
import 'dart:math';
class A {
// Bit Manipulation
int concatenatedBinary(int n) {
int mod = (1e9 + 7).toInt();
int res = 0;
for (int i = 1; i <= n; i++) {
int bitLen = (log(i) ~/ log(2)) + 1;
res = ((res << bitLen) + i) % mod;
}
return res;
}
}
class B {
int concatenatedBinary(int n) {
int res = 0;
int bitLength = 1;
int nextIncrease = 2;
for (int i = 1; i <= n; i++) {
if (i == nextIncrease) {
nextIncrease *= 2;
bitLength++;
}
res = (res << bitLength) | i;
res %= 1000000007;
}
return res;
}
}
class C {
int concatenatedBinary(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
// String binary = int.toBinaryString(i);
String binary = i.toRadixString(2);
sum = ((sum << binary.length) + i) % 1000000007;
}
return sum;
}
}
// Math
class D {
int concatenatedBinary(int n) {
final int modulo = (1e9 + 7).toInt();
int result = 0;
for (int i = 1; i <= n; i++) {
// For each i, we shift left the position of result with * 2,
// while shifting right the position of i with / 2.
int temp = i;
while (temp > 0) {
temp ~/= 2;
result *= 2;
}
// Add the i to the result and get the remainder of modulo.
result = (result + i) % modulo;
}
return result;
}
}
class E {
int concatenatedBinary(int n) {
int digits = 0, MOD = 1000000007;
int result = 0;
for (int i = 1; i <= n; i++) {
/* if "i" is a power of 2, then we have one additional digit in
its the binary equivalent compared to that of i-1 */
if ((i & (i - 1)) == 0) digits++;
result = ((result << digits) + i) % MOD;
}
return result;
}
}