OFFSET
0,3
COMMENTS
This sequence is a self-inverse permutation of the nonnegative integers.
This sequence has similarities with A122155 (where we complement bits between the leftmost and the rightmost 1's).
LINKS
FORMULA
a(2*n + 1) = 2*a(n) + 1.
EXAMPLE
The first terms, in decimal and in binary, are:
n a(n) bin(n) bin(a(n))
-- ---- ------ ---------
0 0 0 0
1 1 1 1
2 2 10 10
3 3 11 11
4 4 100 100
5 5 101 101
6 6 110 110
7 7 111 111
8 10 1000 1010
9 9 1001 1001
10 8 1010 1000
11 11 1011 1011
12 12 1100 1100
13 13 1101 1101
14 14 1110 1110
15 15 1111 1111
16 22 10000 10110
PROG
(PARI) a(n) = { my (b = binary(n)); for (i = 1, #b, if (b[i]==0, forstep (j = #b, 1, -1, if (b[j]==0, for (k = i+1, j-1, b[k] = 1-b[k]; ); return (fromdigits(b, 2)); ); ); ); ); return (n); }
(Python)
def a(n):
b = bin(n)[2:]
zl, zr = b.find('0'), b.rfind('0')
return n if abs(zl-zr) < 2 else int(b[:zl+1]+"".join('0' if bi == '1' else '1' for bi in b[zl+1:zr])+b[zr:], 2)
print([a(n) for n in range(70)]) # Michael S. Branicky, Mar 09 2025
(Python)
def A381839(n): return n^((1<<n.bit_length()-t-1)-1)^(((~n&n+1)<<1)-1) if n and (t:=(s:=bin(n)[2:]).find('0'))!=-1 and s.count('0')>1 else n # Chai Wah Wu, Mar 09 2025
CROSSREFS
KEYWORD
nonn,base,easy
AUTHOR
Rémy Sigrist, Mar 08 2025
STATUS
approved
