Title: Please implement a function, an integer input, the output binary number represents the number 1. For example, to 9 is expressed as a binary 1001, there is a 2 1. Thus, if the input 9, the function output 2.
public class Solution {
public int NumberOf(int num) {
int count = 0;
while (num != 0) {
if ((num & 1) == 1) {
count++;
}
num = num >>> 1; //如果使用>>有符号右移,那么符号位1永远会存在,也就是会产生死循环
}
}
}
复制代码
Implement a function Math.pow, the m-th power of n -.
public class Solution {
public double pow(int m, int n) {
double result = 0;
if (m == 0 && n < 0) {
return -1;
}
int absN = Math.abs(n);
result = calc(m, absN);
if (n < 0) {
result = 1 / result;
}
return result;
}
private int calc(int m, int n) {
int result = 1;
for (int i = 0; i < n; i++) {
result *= m;
}
return result;
}
}
复制代码
Improved calc
private int calc(int m, int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return m;
}
int result = calc(m, n >> 1); //右移1位表示除以2
result *= result;
if ((m & 1) == 1) { //位运算判断是会否为奇数,奇数的二进制第一位一定是1与1做与运算即可判断是否为奇数,代替m%2是否等于0
result *= m;
}
return result;
}
复制代码
Short step a thousand miles.
Reproduced in: https: //juejin.im/post/5d0c1fc4f265da1bbd4b7c61