diff --git a/136_single_number/Makefile b/136_single_number/Makefile new file mode 100644 index 0000000..f992802 --- /dev/null +++ b/136_single_number/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test single_number.c diff --git a/136_single_number/single_number.c b/136_single_number/single_number.c new file mode 100644 index 0000000..d277c56 --- /dev/null +++ b/136_single_number/single_number.c @@ -0,0 +1,22 @@ +#include +#include + +static int singleNumber(int *nums, int numsSize) +{ + int i, s = 0; + for (i = 0; i < numsSize; i++) { + s ^= nums[i]; + } + return s; +} + +int main(int argc, char **argv) +{ + int i, count = argc - 1; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 1]); + } + printf("%d\n", singleNumber(nums, count)); + return 0; +} diff --git a/137_single_number_ii/Makefile b/137_single_number_ii/Makefile new file mode 100644 index 0000000..f992802 --- /dev/null +++ b/137_single_number_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test single_number.c diff --git a/137_single_number_ii/single_number.c b/137_single_number_ii/single_number.c new file mode 100644 index 0000000..bf5beae --- /dev/null +++ b/137_single_number_ii/single_number.c @@ -0,0 +1,71 @@ +#include +#include + +#if 0 +static void singleNumber(int *nums, int numsSize) +{ + int i, xor = 0; + for (i = 0; i < numsSize; i++) { + xor ^= nums[i]; + } + + int mask = 1; + while (!(mask & xor)) { + mask <<= 1; + } + + int zero = 0; + int one = 0; + for (i = 0; i < numsSize; i++) { + if (nums[i] & mask) { + one ^= nums[i]; + } else { + zero ^= nums[i]; + } + } + + printf("%d %d\n", zero, one); +} +#endif + +static int singleNumber(int *nums, int numsSize) +{ +#if 1 + int i, j, count[32], mask = 0; + for (i = 0; i < 32; i++) { + count[i] = 0; + for (j = 0; j < numsSize; j++) { + if ((1 << i) & nums[j]) { + count[i]++; + } + } + mask |= (count[i] % 3) << i; + } + return mask; +#else + int i, ones = 0, twos = 0, threes = 0; + for (i = 0; i < numsSize; i++) { + /* `ones & nums[i]` the result is the bitmask which the bits appeared twice */ + twos |= ones & nums[i]; + /* reset mask twice in `ones` */ + ones ^= nums[i]; + /* count the `three` */ + threes = ones & twos; + /* clear the `ones` and `twos` if the i-th bit had appeared three times. */ + ones &= ~threes; + twos &= ~threes; + } + return ones; +#endif +} + +int main(int argc, char **argv) +{ + int i, count = argc - 1; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 1]); + } + printf("%d\n", singleNumber(nums, count)); + return 0; +}