在Python中将数字循环移位(或旋转)数字 [英] Circularly shifting (or rotating) the digits the digits of a number in Python
本文介绍了在Python中将数字循环移位(或旋转)数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下输入内容:
Suppose I have the following input:
1234
如何获得以下输出?
3412
这是通过将输入的数字循环移位(或旋转)两次来获得的.
This is obtained by circularly shifting (or rotating) the digits of the input twice.
我尝试了以下代码:
number = 1234
bin(number >> 1)
但是它没有产生我所期望的结果.
but it is not producing the results I was expecting.
推荐答案
>>
运算符执行它将 1234
的二进制表示形式向右移动,丢弃最右边的(最低有效)位.
It moves the binary representation of 1234
on place to the right, discarding the rightmost (least significant) bit.
因此,您的代码不会产生 3412
.
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
这篇关于在Python中将数字循环移位(或旋转)数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文