力扣172. 阶乘后的零(取余???位运算出发???)

力扣172. 阶乘后的零

https://leetcode-cn.com/problems/factorial-trailing-zeroes/

设计一个算法,计算出n阶乘中尾部零的个数

 

参考:https://blog.csdn.net/qq_37701948/article/details/104077089

任何一个n的阶乘,其末尾0的个数取决于因数10的个数。只需计算n的阶乘的因数中5的个数

n的阶乘的尾部为0的个数主要取决于其中5的个数。

其实更高级一点,我们换个想法。如果我们直接将n除以5,得到的就是n中所有能整除5的数的个数,为什么呢?把5理解为步长就好理解,5,10,15…,是不是呢?将n/5再除以5,得到的就是n中所有能整除25的数的个数;同样用步长理解,25,50,75…,是不是呢?直到n为0退出循环。这算法的时间复杂度就降低到了log(N/5)log(N/5)log(N/5)。

 

#include "stdafx.h"
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.
		long long count = 0;
		while (n)
		{
			n = n / 5;
			count = n + count;
		}
		return count;
	}
};

int main()
{
	Solution s;
	auto result = s.trailingZeros(123);
    return 0;
}

 

我想用位运算实现除法,好像有点问题。。。

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.
		long long count = 0;
		long long count1 = 0;
		//实现除法功能
		while (n)
		{
			if (n>5)
			{
				for (long long i = 63; i >= 0; i--)//因为longlong型的长度是2的63次方,i理解为倍数
				{
					if ((n >> i) >= 5)
					{
						count1 = count1 + (1 << i);
						n = n - (5 << i);
					}
				}
				count = count + n;
			}
			else
			{
				count= count + n;
				return count;
			}

		}
    }
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值