Answer to Question #298664 in Java | JSP | JSF for Sineka

Question #298664

Bob was quite bored at home and was not telling his mom work in the kitchen. To keep him busy, him mom gave him N integers and asked him to find the total number of pairs of integers such that both the numbers are duplicates of each other. Two numbers are said to be duplicates if they follow the following rule:




. When the numbers are written in the binary forms, the sum of their bits is equal.




Bob is not very good at problem solving. Hence, he approaches you for help. As Bob's friend, you must help him accomplish the task assigned by his mom.

1
Expert's answer
2022-02-16T14:55:06-0500
public class Main {

    public static int binarySum(int number) {
        int sum = 0;
        for (Character digit : Integer.toBinaryString(number).toCharArray()) {
            sum += digit == '1' ? 1 : 0;
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] array = {2, 5, 1, 11, 661, 315, 1635, 35243668, 456, 34345};
        int answer = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (binarySum(array[i]) == binarySum(array[j])) {
                    answer++;
                }
            }
        }
        System.out.println(answer);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS