Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8742273
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:28:16+00:00 2026-06-13T11:28:16+00:00

The problem is how to invert alternate bits of a number, starting from the

  • 0

The problem is how to invert alternate bits of a number, starting from the LSB. Currently what I am doing is first doing a

count = -1
while n:
   n >>= 1
   count += 1

to first find the position of the leftmost set bit, then running a loop to invert every alternate bit:

i = 0
while i <= count:
 num ^= 1<<i
 i += 2

Is there a quick hack solution instead of this rather boring loop solution? Of course, the solution can’t make any asumption about the size of the integer.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:28:17+00:00Added an answer on June 13, 2026 at 11:28 am

    The previous one-liner solution,

    n ^ sum(2**i for i in range(0, len(bin(n))-2, 2))
    

    is an O(lg n) solution, where n is the input number. The asymptotically-much-faster solution shown below runs in time O(lg(lg n)), that is, in time proportional to the log of the number of bits in the input number. Note, the binary search as shown worked ok in tests, but perhaps can be improved.

    Edit: The expression -1<<L is a mask with its high bits set and its L low bits clear. For example, python displays 255 as the value of (-1<<8)&255, and 256 as the value of (-1<<8)&256. The program begins by doubling L (leaving more and more low bits clear) until L exceeds the number of bits in the number v; that is, until (-1<<L)&v is zero. At each doubling of L, it can move R up. The program then uses binary search, repeatedly halving the L-R difference, to find L=R+1 such that v&(-1<<L) == 0 and v&(-1<<R) > 0, to establish that v is L bits long.
    Later, the program doubles the length of an alternating-bits mask k until it is at least L bits long. Then it shifts the mask by one bit if L is odd. (Instead of if L & 1: k = k<<1 it could say k <<= L&1. Note, I interpreted “alternate bits” as beginning with the bit just below the MSB. To instead always toggle bits 0,2,4…, remove the if L & 1: k = k<<1 line.) Then it picks off the low L bits of k by &’ing with (1<<L)-1, ie, with (2**L)-1. Note, the program’s O(lg(lg n)) time bound depends on O(1) logical operations; but as L gets large (beyond a few hundred bits), 1<<L etc become O(lg n) operations.

    def clearaltbits(v):
        if not v:
            return 0
        L, R = 16, 0
        # Find an upper bound on # bits
        while (-1<<L) & v:
            R, L = L, 2*L
        # Binary search for top bit #
        while not (-1<<L) & v:
            m = (L+R)/2
            if (-1<<m) & v:
                R = m
            else:
                L = m
            if L==R+1: break
        print bin(v),'has',len(bin(v))-2,'bits.'
        # Make big-enough alternate-bits mask
        k, b = 0b0101010101010101, 16
        while not (-1<<L) & k:
            k = (k<<b)|k
            b += b
        if L & 1:
            k = k<<1
        k = k & ((1<<L)-1)
        print bin(k^v),'fin'
    
    
    clearaltbits(3**3)
    clearaltbits(5**6)
    clearaltbits(7**17)
    clearaltbits(13**19)
    

    The output from the four function calls is shown below.

    0b11011 has 5 bits.
    0b10001 fin
    
    0b11110100001001 has 14 bits.
    0b10100001011100 fin
    
    0b110100111001001110000011001001100110111010000111 has 48 bits.
    0b100001101100011011010110011100110011101111010010 fin
    
    0b10011110100000000111000001101101000001011000100011000010010000111010101 has 71 bits.
    0b11001011110101010010010100111000010100001101110110010111000101101111111 fin
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a little problem to insert from 2 different table's in C# to
This problem is baffling me: BEGIN; INSERT INTO sub_users(user_id, email) SELECT user_id FROM users
I am facing the problem while inserting data this way. How to insert data
I am doing a conversion with SqlBulkCopy. I currently have an IList collection of
i am trying to make a very simple program that invert the pixels position
I have a number of rows from a database which I want to insert
I have a problem running an insert query via C# OleDbCommand to an Access
I have some problem whith such mysql_query INSERT INTO table VALUES ('', CURDATE()-1) why
I have a problem reading a txt file to insert in the mysql db
I have a little problem where I would like to insert a svn diff

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.