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;
}
};
补充
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位
上一篇: 设计一个算法,计算出n阶乘中尾部零的个数
下一篇: lintcode之逆波兰表达式