2

Suppose I have the following input:

1234

How can I get the following output?

3412

This is obtained by circularly shifting (or rotating) the digits of the input twice.

I have tried the following code:

number = 1234
bin(number >> 1)

but it is not producing the results I was expecting.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Tanya Chaudhary
  • 95
  • 1
  • 4
  • 13

4 Answers4

8

The >> operator does a binary bitshift.

It moves the binary representation of 1234 on place to the right, discarding the rightmost (least significant) bit.

Therefore you code does not result in 3412.

You probably want string rotation instead:

>>> def rotr(string, n):
...     return string[n:] + string[:n]
... 
>>> rotr("1234", 2)
'3412'

You can also convert it back to an integer afterwards

>>> int('3412')
3412
kalehmann
  • 4,821
  • 6
  • 26
  • 36
3

I would convert to string to be able to slice it.

number=1234
right_shift_no = 2
new_number = int(str(number)[right_shift_no:]+str(number)[:right_shift_no])
onno
  • 969
  • 5
  • 9
3

Here's the lazy man's version:

>>> from collections import deque
>>> number = 1234
>>> d = deque(str(number))
>>> d.rotate(2)
>>> result = int(''.join(d))
>>> result
3412
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

If you must stick with numbers (though I'd go with the string option first)

from math import log10, floor
s = 2  # digits to shift by
p = 10 ** s  # that as a power of 10
n = 1234
rhs = n // p  # right hand side of result (here 12)
rhs_n = floor(log10(rhs)) + 1  # number of digits in rhs
rhs + (n % p) * 10 ** rhs_n  # add other digits, n % p, shifted by size of rhs

and all together in a function

from math import log10, floor

def rotate(n, s):
    p = 10 ** s
    rhs = n // p
    return rhs + (n % p) * 10 ** (floor(log10(rhs)) + 1)
joel
  • 6,359
  • 2
  • 30
  • 55