Search code examples
pythondigits

Circularly shifting (or rotating) the digits the digits of a number in Python


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.


Solution

  • 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