问题
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.
回答1:
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
回答2:
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])
回答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
回答4:
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)
来源:https://stackoverflow.com/questions/52555368/circularly-shifting-or-rotating-the-digits-the-digits-of-a-number-in-python