二进制数中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;
}
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));
}
}