题目:请实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如,把9表示成二进制是1001,有2位是1。因此,如果输入9,则该函数输出2。
public class Solution {
public int NumberOf(int num) {
int count = 0;
while (num != 0) {
if ((num & 1) == 1) {
count++;
}
num = num >>> 1; //如果使用>>有符号右移,那么符号位1永远会存在,也就是会产生死循环
}
}
}
复制代码
实现函数Math.pow,求m的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;
}
}
复制代码
改进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;
}
复制代码
不积跬步无以至千里。
转载于:https://juejin.im/post/5d0c1fc4f265da1bbd4b7c61