这里使用的是题库:
https://leetcode.cn/problem-list/xb9nqhhg/?page=1
剑指 Offer 15. 二进制中1的个数
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count=0;
while(n!=0){
n=n&(n-1);
count++;
}
return count;
}
}
剑指 Offer 16. 数值的整数次方
这里参数为long是因为int的最小值(-2147483648)转成正数时会溢出!
class Solution {
public double myPow(double x, int n) {
long N=n;
if(n>0){
return countV(x,N);
}else if(n<0){
return 1/countV(x,-N);
}else{
return 1;
}
}
//求n绝对值的整数次方
private double countV(double x, long n){
double multiplier=x;
long count=0;
double result=1;
long i=1;
while(count<n){
result*=multiplier;
count+=i;
//下次乘数增大
multiplier*=multiplier;
//计数器增大
i*=2;
//判断会不会越界,越界退回原始大小
if(count+i>=n){
i=1;
multiplier=x;
}
}
return result;
}
}
剑指 Offer 17. 打印从1到最大的n位数
class Solution {
public int[] printNumbers(int n) {
int i=1;
while(n-->0){
i*=10;
}
int[] nums=new int[i-1];
for(int j=1;j<i;j++){
nums[j-1]=j;
}
return nums;
}
}
共勉