LeetCode 5620. 连接连续二进制数字
原题链接
中等
作者:
ACSaber
,
2020-12-06 18:13:45
,
所有人可见
,
阅读 264
// 解一
class Solution {
int mod = 1000000007;
public int concatenatedBinary(int n) {
long ans = 0;
for (int i = 1; i <= n; i++) {
ans = (ans << getLength(i)) + i;
ans %= mod;
}
return (int) ans;
}
int getLength(int n) {
for (int i = 31; i >= 0; i--) {
int ans = n >> i & 1;
if (ans == 1) return i + 1;
}
return 0;
}
}
// 解二
class Solution {
int mod = 1000000007;
public int concatenatedBinary(int n) {
long ans = 0;
int[] g = new int[n + 1];
for (int i = 1; i <= n; i++) {
g[i] = g[i / 2] + 1;
ans = (ans << g[i]) + i;
ans %= mod;
}
return (int) ans;
}
}