数与位部分刷题记录

数与位部分刷题记录

数与位的操作

question 7(整数反转)

在这里插入图片描述
answer

class Solution {
   
    public int reverse(int x) {
   
        if(x==0){
   return 0;}
        int sum=0;
        while(x!=0){
   
             if(sum<(Integer.MIN_VALUE)/10||sum>(Integer.MAX_VALUE)/10){
   
                return 0;
            }  

            sum=sum*10+(x%10);
             x=x/10;
              
           
        }
        return sum;
    }
}

question9(回文数)

在这里插入图片描述
answer

class Solution {
   
    public boolean isPalindrome(int x) {
   
        //若是回文,则正反都一样,把数字倒序存储,比较是否相等
        if(x<0){
   return false;}
        int reverse=0;
        int temp=x;
        while(temp!=0){
   
            reverse=reverse*10+temp%10;
            temp=temp/10;
        }
        if(reverse==x){
   
            return true;
        }
        return false;
    }
}

question479(最大回文数乘积)

在这里插入图片描述
answer
遍历暴力解会超时

class Solution {
   
    public int largestPalindrome(int n) {
   
        if(n==1){
   return 9;}
        int max=(int)Math.pow(10,n)-1;
        int res=0;
        //枚举回文数的左半部分
        for(int left=max;res==0;left--){
   
            //构造回文数p
            long p=left;
            int x=left;
            //加上回文数的右半部分
            while(x!=0){
   
                p=p*10+x%10;
                x/=10;
            }
            //x*x可能会溢出,用long
            for(long i=max;i*i>=p;i--){
   
                //i是p的因子
                if(p%i==0){
   
                    res=(int)(p%1337);
                    break;
                }
            }
        }
        return res;
    }

}

question 564*、

question 231(2的幂)

在这里插入图片描述
answer

class Solution {
   
    public boolean isPowerOfTwo(int n) {
   
        while(n>1){
   
            int temp=n%2;
            if(temp!=0){
   
                return false;
            }
            n=n/2;
        }
        if(n==1){
   
            return true;
        }
        return false;
    }
}
class Solution {
   
    public boolean isPowerOfTwo(int n) {
   
        return n > 0 && (n & (n - 1)) == 0;
    }
}

question326(3的幂)

在这里插入图片描述

class Solution {
   
    public boolean isPowerOfThree(int n) {
   
        while(n!=0&&n%3==0){
   
            n=n/3;
        }
        if(n==1){
   
            return true;
        }
        return false;

    }
}

question504(七进制数)

在这里插入图片描述

class Solution {
   
    public String convertToBase7(int num) {
   
        StringBuilder sb=new StringBuilder();
        if(num==0){
   
            return "0";
        }
        boolean flag=num<0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值