欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Lintcode:2. Trailing Zeros

程序员文章站 2022-07-15 18:47:22
...

Description:

Write an algorithm which computes the number of trailing zeros in n factorial.

Have you met this question in a real interview?

Example:

Input:  11
Output: 2

Explanation: 
11! = 39916800, so the output should be 2
Input:  5
Output: 1

Explanation: 
5! = 120, so the output should be 1.

Challenge:

O(log N) time

Analysis:

the number of ‘5’ equals the number of ‘0’. Because the number of even in n! is greater than the number of ‘5’. At the same time, even multiply 5, there is a 0(trailing zeros).

Mycode:

class Solution {
public:
    /*
     * @param n: A long integer
     * @return: An integer, denote the number of trailing zeros in n!
     */
    long long trailingZeros(long long n) {
        // write your code here, try to do it without arithmetic operators.
        if(n==0||n==1) return 0;
        long num=0;  //long类型至少32位,且至少与int一样长
                     //long long类型至少64位,且至少与long一样长
                     //int类型32位,至少与short一样长
                     //short类型16位
        while(n)
        {
            n/=5;
            num+=n;
        }
        return num;
    }
};

Lintcode:2. Trailing Zeros
补充
float范围的计算:4字节,32位浮点数,第1位符号位,有23位是用来表示小数的,其余8位指数部分
23位最大的就是全部是1,也就是0.111…111(23个1,此数是二进制),但是IEEE 754标准规定了一个隐含的1(用于节省1个位的空间),不在这23位中,前面0.11…11实际上就是1.111…111(24个1),非常接近于2,所以小数就是2。
自此float的范围为-2128 ~ +2128,也即十进制:-3.40E+38 ~ +3.40E+38
float:2^23 = 8388608,一共七位,这意味着最多能有7位有效数字
而double是8字节,64位

相关标签: lintcode题目