-1

Trying to create a small program that takes in positive integers and converts it into reverse binary.

I've gotten this far:

import math
integer = int(input())

while integer > 0:
    x = integer % 2
    print(int(math.floor(x)), end='')
    integer = integer / 2

The problem with this is that the output would have unnecessary trailing 0s. For example, if the input is 12, the output would be 0011000......

I've tried the int function to remove floats, I also tried floor function to round up(albeit I might've done it wrong).

Could the problem be a lack of sentinel value?

  • 5
    `integer // 2` [is your friend](https://www.youtube.com/watch?v=tlADJpNtS_s&t=8s) –  Oct 23 '22 at 17:01
  • or `integer >> 1` – Tom McLean Oct 23 '22 at 17:05
  • Or even `bin(integer)[2:][::-1]` – RufusVS Oct 23 '22 at 17:14
  • Welcome to Stack Overflow. The underlying problem is that "removing" floats in the ways that you describe doesn't address the problem. The `integer` variable is a floating-point value, because of `integer = integer / 2`. Please see the linked duplicate to understand the problem and the normal solution (which is as simple as using `//` instead). – Karl Knechtel Oct 25 '22 at 01:17

3 Answers3

0

It sounds like you have reversed a binary number like this:

def reverse_bits(n):
    res = 0
    for i in range(n.bit_length(), -1, -1):
        if n & (1 << i):
            res += 1 << (n.bit_length() - i)
    return res

bin(reverse_bits(12))  # '0b110'

You can bit shift to the right, until there is a 1 in the rightmost bit, to remove trailing zeros:

def remove_trailing_zeros(n):
    while not n & 1:
        n = n >> 1
    return n

All together:

bin(remove_trailing_zeros(reverse_bits(12)))
Out[11]: '0b11'
Tom McLean
  • 5,583
  • 1
  • 11
  • 36
  • Not sure what this dude wants, but I'm pretty sure it's not to print the binary representation of 'the input divided by the largest power of 2 which divides it'. Sounds like he's aiming at printing the binary representation of the input in reversed order (at least according to the example in the question). –  Oct 23 '22 at 17:11
  • @bbbbbbbbb I was a bit confused by his question, i added how to reverse a binary number with the addition of removing the trailing zeros – Tom McLean Oct 23 '22 at 17:22
-1

use // instead of / in division

-1

Here is an alternate approach:

integer = 3
print (bin(integer)[2:][::-1])
desertnaut
  • 57,590
  • 26
  • 140
  • 166