位运算
唯一的元素值
package com.lanqiao;
import java.util.Random;
public class UniquePairedNumbers {
public static void main(String[] args) {
int N = 11;
int[] a = new int[N];
for (int i = 0; i < a.length - 1; i++)
a[i] = i + 1;
a[a.length - 1] = new Random().nextInt(N - 1) + 1;
for (int b : a) {
System.out.print(b + " ");
}
System.out.println();
int x1 = 0, x2 = 0, ans = 0;
for (int i = 1; i <= a.length - 1; i++) {
x1 = x1 ^ i;
}
for (int i = 0; i < a.length; i++) {
x2 = x2 ^ a[i];
}
ans = x1 ^ x2;
System.out.println(ans);
}
}
二进制中1的个数
package com.lanqiao;
import java.util.Scanner;
public class NumberOfOneInBinary {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int ans = 0;
System.out.println(Integer.toString(N, 2));
for (int i = 0; i < 32; i++) {
if ((N & (1 << i)) == (1 << i)) {
ans++;
}
}
System.out.println(ans);
ans = 0;
for (int i = 0; i < 32; i++) {
if (((N >> i) & 1) == 1) {
ans++;
}
}
System.out.println(ans);
ans = 0;
while (N != 0) {
N = (N - 1) & N;
ans++;
}
System.out.println(ans);
}
}
交换奇偶位
package com.lanqiao;
import java.util.Scanner;
public class OddEvenExchange {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int bin = scanner.nextInt();
System.out.println(bin);
System.out.println(Integer.toBinaryString(bin));
bin = solution(bin);
System.out.println(bin);
System.out.println(Integer.toBinaryString(bin));
}
private static int solution(int bin) {
int even = bin & 0xaaaaaaaa;
int odd = bin & 0x55555555;
return (even >> 1) ^ (odd << 1);
}
}
出现K次和出现1次
package com.lanqiao;
public class KOccurrencesAndOneOccurrence {
public static void main(String[] args) {
int[] arr = {3,3,3,2,2,2,7,7,7,9,0,0,0};
int maxLen = 0;
int n = arr.length;
int k = 3;
char[][] cache = new char[n][];
for (int i = 0; i < n; i++) {
cache[i] = new StringBuilder(Integer.toString(arr[i],k)).reverse().toString().toCharArray();
if (cache[i].length > maxLen) {
maxLen = cache.length;
}
}
int[] ans = new int[maxLen];
for (int i = 0; i < n; i++) {
for (int j = 0; j < maxLen; j++) {
if (j >= cache[i].length) {
ans[j] += 0;
} else {
ans[j] += (cache[i][j] - '0');
}
}
}
int res = 0;
for (int i = 0; i < ans.length; i++) {
res += (ans[i] % k) * (int) (Math.pow(k, i));
}
System.out.println(res);
}
}