从整数中删除尾随零的更好方法 [英] Better way to remove trailing zeros from an integer

查看:100
本文介绍了从整数中删除尾随零的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个没有经验的程序员.我正在尝试从整数中删除尾随零,这是我在python中设置的项目的结果.

I'm an inexperienced programmer. I'm trying to remove trailing zeros from a whole number, an integer, for a project I've set myself in python.

我已经做到了,但是必须有比我炮制的怪兽更好的方法!

I have managed to do this but there must be a better way than the monstrosity I have concocted!

def removeZeros(number):
    return int(str(int(str(number)[::-1]))[::-1])

基本上,我是将整数转换为字符串,然后将其反转,然后将其转换为整数,这将删除当前的前导零,然后将其转换为字符串并反转.最后将其转换为整数以返回它.

Essentially I'm turning the integer into a string, reversing the string, turning it back into an integer---which removes the now leading zeros, turning it back into a string and reversing it; and finally turning it back into an integer to return it.

任何帮助将不胜感激.

推荐答案

只需使用您也可以在不将数字转换为字符串的情况下执行此操作,这应该会更快一些:

You could also do it without converting the number to a string, which should be slightly faster:

def remove_zeros(number):
    while number % 10 == 0:
        number //= 10
    return number

这篇关于从整数中删除尾随零的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆