数与位2

数字的位操作2

231. 2 的幂 - 力扣(LeetCode)

1
2
3
4
5
class Solution {
public boolean isPowerOfTwo(int n) {
return ( n > 0&&( n & (n - 1))== 0);
}
}

342. 4的幂 - 力扣(LeetCode)

1
2
3
4
5
6
class Solution {
public boolean isPowerOfFour(int n) {
if(n == 0) return false;
return ((n & (n - 1)) == 0 && (n & (0xaaaaaaaa)) == 0);
}
}

326. 3 的幂 - 力扣(LeetCode)

1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean isPowerOfThree(int n) {
long x = 1;
while(x != n){
x *= 3;
if(x > n) return false;
}
return true;
}
}

1162261467是3 ^ 19

1
2
3
4
5
class Solution {
public boolean isPowerOfThree(int n) {
return n > 0 && (1162261467 % n) == 0;
}
}

504. 七进制数 - 力扣(LeetCode)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public String convertToBase7(int num) {
if(num == 0) return "0";
boolean negative = num < 0;
num = Math.abs(num);
StringBuffer digits = new StringBuffer();
while(num > 0){
digits.append(num % 7);
num /= 7;
}
if(negative) digits.append('-');
return digits.reverse().toString();
}
}

263. 丑数 - 力扣(LeetCode)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public boolean isUgly(int n) {
if(n <= 0) return false;
int[] v = {2,3,5};
for(int g : v){
while(n % g == 0){
n /= g;
}
}
return n == 1;
}
}

564. 寻找最近的回文数 - 力扣(LeetCode)

这个题目我用暴力超时了,但是题解方法太难了,过几天再写吧

暴力超时法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public String nearestPalindromic(String s) {
if(s.equals("1")) return "0";
long n = s.length();
long x = Integer.parseInt(s);
long y = (int)Math.pow(10 ,n + 1) - 1;

int a0 = Integer.MIN_VALUE;
for(int i = 0; i < x; i++){
if(judge(i)) {
a0 = Math.max(a0, i);
}
}
long a1 = Integer.MAX_VALUE;
for(long i = y; i > x; i--){
if(judge(i)){
a1 = Math.min(a1, i);
}
}
long ret0 = Math.abs(x - a0);
long ret1 = Math.abs(x - a1);
return ret0 > ret1 ? String.valueOf(a1) : String.valueOf(a0);
}

boolean judge(long x){
long revert = 0;
while(x > revert){
revert = revert*10 + x%10;
x /= 10;
}
return x == revert || x == revert/10;
}
}

数与位2
http://example.com/2024/04/20/数与位2/
作者
nianjx
发布于
2024年4月20日
许可协议