Python实现数字向上取整为首位数非零其余为零的数值
Python实现数字向上取整至首位非零其余为零的数值
需求是将正整数向上取整至下一个仅首位数非零、其余位数均为零的数值,示例如下:
123→2008472→90005→10999→1000
方法一:纯数学计算法
通过对数运算确定数字的数量级,结合首位数字判断进位逻辑,无需字符串转换。
import math def round_up_to_first_non_zero(n): if n <= 0: raise ValueError("仅支持正整数输入") # 计算当前数字的数量级(如123对应10^2=100) magnitude = 10 ** math.floor(math.log10(n)) first_digit = n // magnitude # 首位为9时,进位到下一个数量级(如999→1000) if first_digit == 9: return magnitude * 10 return (first_digit + 1) * magnitude
测试验证:
print(round_up_to_first_non_zero(123)) # 200 print(round_up_to_first_non_zero(8472)) # 9000 print(round_up_to_first_non_zero(5)) # 10 print(round_up_to_first_non_zero(999)) # 1000
方法二:字符串处理法
借助字符串操作提取首位数字和长度,直接构造目标数值,无需依赖数学库。
def round_up_to_first_non_zero_str(n): if n <= 0: raise ValueError("仅支持正整数输入") s = str(n) first_digit = int(s[0]) num_length = len(s) if first_digit == 9: return 10 ** num_length return (first_digit + 1) * (10 ** (num_length - 1))
测试验证:
print(round_up_to_first_non_zero_str(123)) # 200 print(round_up_to_first_non_zero_str(8472)) # 9000 print(round_up_to_first_non_zero_str(5)) # 10 print(round_up_to_first_non_zero_str(999)) # 1000
内容的提问来源于stack exchange,提问作者blaylockbk
相关产品推荐
相关产品推荐

