《剑指offer》每日三题(第二天)

这里使用的是题库:
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;
    }
}

共勉
请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值