find unique number among array

Given an array, find the unique number which shows only once whereas other numbers show 3 times.

Total Code:

import java.util.*;

class findUniq {
	public static int findUniq(int[] arr) {
		int[] tmp = new int[32];
		for(int i = 0; i< arr.length; i++) { 			
                   for(int j = 31; j >= 0 && arr[i] != 0; j--) {
				tmp[j] += arr[i]%2;
				arr[i] = arr[i] >> 1;
			}
		}
		
		int res = 0;
		int product = 1;
		for(int j = 0; j<=31; j++) { 			
                    tmp[31-j] = tmp[31-j]%3; 			
                    res += tmp[31-j]*product; 			
                    product *= 2; 		
                } 		
             return res; 	
        }
 	
        public static void main(String[] args) 	
        { 		
                int[] arr = {1,1,1,4,4,4,2,2,2,5}; 		
                // print 5 		
                System.out.println(findUniq(arr)); 		
                // int num = 8; 		
                // int[] tmp = new int[32]; 		
                // for(int i = 31; i >= 0 && num != 0; i--) {
		// 	tmp[i] = num%2;
		// 	num = num >> 1;
		// }
		// print 0 0 0  . . . 0 0 0 1 0 0 0
		// System.out.println(Arrays.toString(tmp));
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s