Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3b611b2

Browse files
Create 3677.Count-Binary-Palindromic-Numbers.cpp
1 parent cab7e48 commit 3b611b2

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using LL = long long;
2+
class Solution {
3+
public:
4+
LL reverseBits(LL x) {
5+
LL r = 0;
6+
while (x>0) {
7+
r = r*2+(x&1);
8+
x>>=1;
9+
}
10+
return r;
11+
}
12+
13+
LL build(LL half, int L) {
14+
int h = (L+1)/2;
15+
int k = L-h;
16+
if (L%2==0) {
17+
return (half<<k) | reverseBits(half);
18+
} else {
19+
return (half<<k) | reverseBits(half>>1);
20+
}
21+
}
22+
23+
int countBinaryPalindromes(long long n) {
24+
if (n==0) return 1;
25+
int maxLen = floor(log2(n)) + 1;
26+
27+
LL ret = 1;
28+
for (int L=1; L<maxLen; L++) {
29+
int h = (L+1)/2;
30+
long long mn = 1LL<<(h-1);
31+
long long mx = (1LL<<h)-1;
32+
ret += mx-mn+1;
33+
}
34+
35+
{
36+
int L = maxLen;
37+
int h = (L+1)/2;
38+
long long mn = 1LL<<(h-1);
39+
long long mx = (1LL<<h)-1;
40+
LL lo = mn, hi = mx;
41+
while (lo < hi) {
42+
LL mid = hi-(hi-lo)/2;
43+
LL pal = build(mid, L);
44+
if (pal <= n) {
45+
lo = mid;
46+
} else {
47+
hi = mid-1;
48+
}
49+
}
50+
LL pal = build(hi, L);
51+
if (pal <= n)
52+
ret += (LL)(hi-mn+1);
53+
}
54+
55+
return ret;
56+
}
57+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /