Example: Given a positive integer n, how can we count the number of digits in its decimal representation? One way to do it is convert the integer into a string and count the characters. Here, though, we will use only arithmetical operations instead. We can simply keep dividing the number by ten and count how many steps are needed to obtain 0.
1 result = 0 2 while n > 0: 3 n = n // 10 4 result += 1
是的,这段代码是用Python编写的,用于计算一个整数在十进制表示下有多少位。以下是每行的详细解释:
所以,当这个循环结束时,result的值就是整数在十进制表示下的位数。
作者: 丙丁先生, 来源:面包板社区
链接: https://mbb.eet-china.com/blog/uid-me-3996156.html
版权声明:本文为博主原创,未经本人允许,禁止转载!
文章评论(0条评论)
登录后参与讨论