Find a number that appears only once in an array where other numbers appear k times
Title description
Given an integer array arr and an integer k greater than 1. It is known that only one number appears once in arr, and the other numbers appear k times. Please return the number that appears once.
Enter a description:
The input contains two lines, the first line contains two integers n and k, 1 <= n <= 1 0 5, 1 <k <= 100 1<=n<=10^5, 1 <k <= 1001<=n<=105,1<k<=1 0 0 , n represents the length of the array arr, and the n integers in the second row represent the array arr. Each number in the array arr is a 32-bit integer.
Output description:
Output an integer, representing the only number that appears once.
Example 1
enter
7 3
5 4 1 1 5 1 5
Output
4
answer:
If k identical k-ary numbers are added without carry, the result of the addition must be a k-ary number with 0 in each digit. So we can directly add each bit in the k-ary of each element without carry, and the final result is the element that appears once.
Code:
#include <cstdio>
using namespace std;
int n, k;
int bit[32];
int main(void) {
scanf("%d%d", &n, &k);
int val, idx;
int up = 0;
while ( n-- ) {
scanf("%d", &val);
idx = 0;
while ( val ) {
bit[ idx ] += val % k;
bit[ idx ] %= k;
val /= k;
++idx;
}
if ( idx > up ) up = idx;
}
int ret = 0;
for ( int i = up - 1; i >= 0; --i )
ret = ret * k + bit[ i ];
return 0 * printf( "%d\n", ret );
}