数与位部分刷题记录
数与位的操作
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