二进制数中的个数

二进制数中1的个数

在这里插入图片描述

public class Solution {
	//方法一:直接按照求二进制,然后统计余数出现的次数
	 public int hammingWeight(int n) {
		 int c=0; //计数器
		 while(n>0)
		 {
			 if(n%2==1) 
				 ++c;
			 n=n/2;
		 }
		 return c;
	    }
	   
	  //方法二:将n和n-1的二进制进行按位运算,运算后的结果赋给n,直到n为零,特点是循环的次数与n无关,只与二进制中1的次数有关
	 public int hammingWeight2(int n)
	 {
		 int c=0;
		 while(n>0)
		 {
			 c++;
			 n=n&(n-1);
		 }
		 return c;
	 }
	 public static void main(String[] args)
	 {
		 Solution ss=new Solution();
		 System.out.println(ss.hammingWeight(9));
		 System.out.println(ss.hammingWeight2(9));
	 }
}

实现double power()函数

在这里插入图片描述

class Solution {
	

	 public double myPow(double x, int n) 
	 {
		 double t=1.0;
		 if(n==0)
		 {
			 return 1.0;
		 }
		 
		 for(int i=0;i<n;i++)
		 {
			 t=t*x;
		 }
	     if(n>0)
	    	 return t;
	     else
	    	 return 1.0/t;
	 }
	 public static void main(String[] args)
	 {
		 Solution ss=new Solution();
		 System.out.println(ss.myPow(2.0, 10));
	 }
}

发布了16 篇原创文章 · 获赞 1 · 访问量 1252

猜你喜欢

转载自blog.csdn.net/cf1169983240/article/details/104417661