反转数字算法
Reverse a number algorithm
我正在考虑反转整数的方法,我想到了这个:
num = 123456
power = len(str(num))
result = 0
for i in range(1, power):
result += (num % 10) * 10**(power - i)
num = int(num / 10)
result += num
print(result)
我正在研究其他人的算法,但我还没有看到任何人将这种方法与指数一起使用。
比如他的不是我的:
public long reverse(long x)
{
long result = 0;
while (x != 0)
{
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
我的算法是不是很差?比如,会不会因为指数部分,计算倒数需要更多的时间?
while
和 for
循环在两个解决方案中经历相同次数的迭代。所以从这个意义上来说,它并不逊色。
您的解决方案包含从数字到字符串的转换,因此可以避免。但是由于 Python 允许您轻松地进行此类转换,并且如果这提高了代码的可读性,那么我认为这不会使您的代码变差。虽然说过考虑问题评论中提出的解决方案 :)
我正在考虑反转整数的方法,我想到了这个:
num = 123456
power = len(str(num))
result = 0
for i in range(1, power):
result += (num % 10) * 10**(power - i)
num = int(num / 10)
result += num
print(result)
我正在研究其他人的算法,但我还没有看到任何人将这种方法与指数一起使用。
比如他的不是我的:
public long reverse(long x)
{
long result = 0;
while (x != 0)
{
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
我的算法是不是很差?比如,会不会因为指数部分,计算倒数需要更多的时间?
while
和 for
循环在两个解决方案中经历相同次数的迭代。所以从这个意义上来说,它并不逊色。
您的解决方案包含从数字到字符串的转换,因此可以避免。但是由于 Python 允许您轻松地进行此类转换,并且如果这提高了代码的可读性,那么我认为这不会使您的代码变差。虽然说过考虑问题评论中提出的解决方案 :)