Source: https://leetcode.com/contest/weekly-contest-218/problems/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 10^9 + 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 <= 10^5
思路:递推
令
f
(
n
)
f(n)
f(n)表示1至n的二进制表示连起来的值,则
f
(
n
)
=
(
f
(
n
−
1
)
<
<
n
的
位
数
)
+
n
f(n)=(f(n-1)<<n的位数)+n
f(n)=(f(n−1)<<n的位数)+n
求一个数的二进制表示里1的个数可以用内置函数__builtiin_popcount()
但是计算数的二进制表示的位数只能自己写了(以下为计算1至n的二进制表示的位数)
O ( n lg n ) O(n\lg n) O(nlgn)的方式:
int get_len(int x){
int res=0;
while(x){
res++,x>>=1;
}
return res;
}
O ( n ) O(n) O(n)的方式(递推):
vector<int> dig(n+1);
for(int i=1;i<=n;i++){
dig[i]=dig[i/2]+1;
}
所以这题的代码是
class Solution {
public:
const int mod=1e9+7;
typedef long long ll;
int concatenatedBinary(int n) {
vector<int> dig(n+1);
dig[1]=1;
int ans=0;
for(int i=1;i<=n;i++){
dig[i]=dig[i/2]+1;
ans=(i+((ll)ans<<dig[i]))%mod;
}
return ans;
}
};