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

		}
    }
};
发布了23 篇原创文章 · 获赞 0 · 访问量 137

猜你喜欢

转载自blog.csdn.net/qq_35683407/article/details/105375104