fork(10) download
  1. import java.io.*;
  2.  
  3. // Problem Description:
  4. // In an array, all numbers appear three times except one which only
  5. // appears once. Please find the unique number.
  6.  
  7. class Ideone
  8. {
  9. public static int FindNumberAppearingOnce(int[] numbers) {
  10. int[] bitSum = new int[32];
  11. for(int i = 0; i < 32; ++i) {
  12. bitSum[i] = 0;
  13. }
  14.  
  15. for(int i = 0; i < numbers.length; ++i) {
  16. int bitMask = 1;
  17. for(int j = 31; j >= 0; --j) {
  18. int bit = numbers[i] & bitMask;
  19. if(bit != 0) {
  20. bitSum[j] += 1;
  21. }
  22.  
  23. bitMask = bitMask << 1;
  24. }
  25. }
  26.  
  27. int result = 0;
  28. for(int i = 0; i < 32; ++i) {
  29. result = result << 1;
  30. result += bitSum[i] % 3;
  31. }
  32.  
  33. return result;
  34. }
  35.  
  36. //////////////////////////////////////////////////////////////
  37. // Test Code Begins:
  38. //////////////////////////////////////////////////////////////
  39. private static void test(String testName, int[] numbers, int expected) {
  40. int result = FindNumberAppearingOnce(numbers);
  41. if(result == expected) {
  42. System.out.println(testName + " passed.");
  43. }
  44. else {
  45. System.out.println(testName + " FAILED.");
  46. }
  47. }
  48.  
  49. private static void test1() {
  50. int[] numbers = {1, 1, 2, 2, 2, 1, 3};
  51. int expected = 3;
  52. test("Test1", numbers, expected);
  53. }
  54.  
  55. private static void test2() {
  56. int[] numbers = {4, 3, 3, 2, 2, 2, 3};
  57. int expected = 4;
  58. test("Test2", numbers, expected);
  59. }
  60.  
  61. private static void test3() {
  62. int[] numbers = {4, 4, 1, 1, 1, 7, 4};
  63. int expected = 7;
  64. test("Test3", numbers, expected);
  65. }
  66.  
  67. private static void test4() {
  68. int[] numbers = {-10, 214, 214, 214};
  69. int expected = -10;
  70. test("Test4", numbers, expected);
  71. }
  72.  
  73. private static void test5() {
  74. int[] numbers = {-209, 3467, -209, -209};
  75. int expected = 3467;
  76. test("Test5", numbers, expected);
  77. }
  78.  
  79. private static void test6() {
  80. int[] numbers = {1024, -1025, 1024, -1025, 1024, -1025, 1023};
  81. int expected = 1023;
  82. test("Test6", numbers, expected);
  83. }
  84.  
  85. private static void test7() {
  86. int[] numbers = {-1024, -1024, -1024, -1023};
  87. int expected = -1023;
  88. test("Test7", numbers, expected);
  89. }
  90.  
  91. public static void main (String[] args) {
  92. test1();
  93. test2();
  94. test3();
  95. test4();
  96. test5();
  97. test6();
  98. test7();
  99. }
  100. }
Success #stdin #stdout 0.07s 380160KB
stdin
int
stdout
Test1 passed.
Test2 passed.
Test3 passed.
Test4 passed.
Test5 passed.
Test6 passed.
Test7 passed.