1356. Sort Integers by The Number of 1 Bits

1356. Sort Integers by The Number of 1 Bits

class Solution {
public int[] sortByBits(int[] arr) {
		Integer[] arrObject = new Integer[arr.length];
		for (int i = 0; i < arr.length; i++) {
			arrObject[i] = arr[i];
		}
		Arrays.sort(arrObject, new Comparator() {

			@Override
			public int compare(Integer o1, Integer o2) {
				if (countOnes(o1) == countOnes(o2))
					return o1.compareTo(o2);
				else if (countOnes(o1) > countOnes(o2))
					return 1;
				else
					return -1;

			}
		});

		for (int i = 0; i < arr.length; i++) {
			arr[i] = arrObject[i];
		}
		return arr;
	}

	public static int countOnes(int n) {
		int count = 0;
		while (n != 0) {
			n = n & (n - 1);
			count++;
		}
		return count;
	}
}

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 )

Connecting to %s