Leetcode 阶乘后的零【Java&Golang&Rust】

阶乘后的零

题目描述

给定一个整数 n ,返回 n! 结果中尾随零的数量。

提示 n! = n * (n - 1) * (n - 2) * … * 3 * 2 * 1

示例

示例 1:

输入:n = 3
输出:0
解释:3! = 6 ,不含尾随 0

示例 2:

输入:n = 5
输出:1
解释:5! = 120 ,有一个尾随 0

示例 3:

输入:n = 0
输出:0

提示:

0 <= n <= 104

解题思路

  1. 0的贡献来源于:本身有0,或是偶数与5的倍数相乘获得;
  2. 由于偶数的个数一定比5的倍数的个数多,因而对于这种情况只考虑5的倍数的个数
  3. 本身有0的数恰好是5的倍数,拥有的0的个数恰好又与是5^n的倍数的n相等
  4. 综上,只需要计算阶乘中各个5的次方数的个数和即可。【因为是多少次方就会在其中被计算多少次,因而不需要考虑是否会有重复计算的问题】

Java实现

import java.util.Scanner;

/**
 * @author wyf
 * @datetime 2023/6/1 21:08
 **/
public class Main {


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.println(trailingZeroes(n));
    }

    private static long a(int n) {
        long sum = 1;
        for (int i = 1; i <= n; i++) {
            sum *= i;
        }
        return sum;
    }

    public static int trailingZeroes(int n) {
        int count=0;
        while (n >=5){
            n = n/5;
            count+=n;
        }
        return count;
    }
}

Golang实现

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	fmt.Println(trailingZeroes(n))
}

func trailingZeroes(n int) int {
	count := 0
	for n >= 5 {
		n /= 5
		count += n
	}
	return count
}

Rust实现

use std::io;

pub fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input)
        .ok()
        .expect("Failed to read line");
        
    let i: i32 = match input.trim().parse() {
        Ok(num) => num,
        Err(_) => {
             println!("请输入整数,请勿输入无关符号!");
             return;
        }
    };

    println!("{}", trailing_zeroes(i))
    
}

fn trailing_zeroes(m : i32) -> i32{
    let mut count = 0;
    let mut n = m;
    while n>=5 {
        n/=5;
        count+=n;
    }
    return count;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北方的孤夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值