数与位

数字的位操作

7. 整数反转 - 力扣(LeetCode)

有一点东西,但不多

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int reverse(int x) {
int res = 0;
while(x != 0){
int v = x % 10;
if(res > 214748364 || (res == 214748364 && v > 7)) return 0;
else if(res < -214748364 || (res == -214748364) && v < -7) return 0;
x /= 10;
res = res*10 + v;
}
return res;
}
}

9. 回文数 - 力扣(LeetCode)

这种方法就是练一下kmp算法,主要是这东西我写一次,错一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isPalindrome(int x) {
if(x < 0) return false;
String s = String.valueOf(x);
int n = s.length();
String ss = " " + s;
int[] next = new int[n + 1];
for(int i = 2, j = 0; i <= n; i++){
while(j > 0 && ss.charAt(j + 1) != ss.charAt(i)) j = next[j];
if(ss.charAt(j + 1) == ss.charAt(i)) next[i] = ++j;
}
int len = 0;
for(int i = n; i > 0; i--){
while(len > 0 && ss.charAt(len + 1) != ss.charAt(i)) len = next[len];
if(ss.charAt(len + 1) == ss.charAt(i)) len++;
}
return len == n;
}
}

479. 最大回文数乘积 - 力扣(LeetCode)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int largestPalindrome(int n) {
if(n == 1) return 9;
//选一个n位数字中最大的值,从大到小逐个遍历
long max = (long)Math.pow(10, n) - 1;
for(long i = max; i > 0; i--){
long a = i, b = i;
//构造一个回文数
while(b != 0){
a = a*10 + b%10;
b /= 10;
}
//j至少要保证 j^2是大于构造的回文数(a)的,否则j*(j - 1)就一定小于a
for(long j = max; j * j > a; j--){
if(a % j == 0) return (int)(a % 1337);
}
}
return -1;
}
}

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