有关阶乘的两个问题

 //(方法一、判定5的个数O(Nlog(5)N))给定一个非负整数N,返回N!结果的末尾为0的数量
    public static int getZero(int n)
    {
    	 if(n<0)
    	 {
    	 	return 0;
    	 }
    	  int res=0;
    	  int cur=0;
    	  for(int i=5;i<n+1;i+=5)
    	  {
                 cur=i;
                 while(cur%5==0) //计算有多少个5组成
                 {
                 	res++;
                 	cur/=5;
                 }
    	  }
           return res;
    }

  //(方法二:公式法 O(log(5)N))
    public static int  getZero02(int n)
    {
    	  if(n<0)
    	  {
    	  	 return 0;
    	  }
    	  int res=0;
    	  while(n!=0)
    	  {
    	  	  res+=n/5;
              n/=5;
    	  }
    	  return res;
    } 

二、进阶问题解法

  //******************进阶问题***********************
    public static int rigthOne01(int n)
    {
    	 if(n<1)
    	 {
    	 	 return -1;
    	 }
    	 int res=0;
    	 while(n!=0)
    	 {
    	 	 n>>>=1;
    	 	 res+=n;
    	 }
    	 return res;

    }

    public static int rigthOne02(int n)
    {
    	  if(n<1)
    	  {
    	  	 return -1;
    	  }
    	  int temp=n;
    	  int ones=0;
    	  while(temp!=0)
    	  {
    	  	 ones+=(temp&1)!=0?1:0;
    	  	 temp>>>=1;
    	  }
    	  return n-ones;

    }
public static void main(String[]args)
	{
        //System.out.println("Hello");
        int n=10;
        System.out.println(getZero(n));
        System.out.println(getZero02(n));
         
        ///**********进阶问题********************
        int n2=10;
        System.out.println(rigthOne01(n2));
        System.out.println(rigthOne02(n2));
	   
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值