The number of the binary number

Number 1 in the binary number

Here Insert Picture Description

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));
	 }
}

Achieve double power () function

Here Insert Picture Description

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));
	 }
}

Published 16 original articles · won praise 1 · views 1252

Guess you like

Origin blog.csdn.net/cf1169983240/article/details/104417661