Lintcode:2. Trailing Zeros

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;
    }
};

在这里插入图片描述
补充
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位

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值