2595. Number of Even and Odd Bits

Difficulty:
Related Topics:
Similar Questions:

Problem

You are given a positive integer n.

Let even denote the number of even indices in the binary representation of n (0-indexed) with value 1.

Let odd denote the number of odd indices in the binary representation of n (0-indexed) with value 1.

Return **an integer array *answer* where **answer = [even, odd].

Example 1:

Input: n = 17
Output: [2,0]
Explanation: The binary representation of 17 is 10001.
It contains 1 on the 0th and 4th indices.
There are 2 even and 0 odd indices.

Example 2:

Input: n = 2
Output: [0,1]
Explanation: The binary representation of 2 is 10.
It contains 1 on the 1st index.
There are 0 even and 1 odd indices.

Constraints:

Solution (Java)

class Solution {
    public int[] evenOddBit(int n) {
        String str1 = Integer.toBinaryString(n);
                StringBuffer sc = new StringBuffer(str1);
                sc.reverse();
                String str =sc.toString();

        int Even_count = 0;
        int Odd_count = 0;
        int[] arr = new int[2];

        for(int i=0 ; i<str.length();i++){
            if((str.charAt(i) == '1') && i%2==0){
                Even_count++;
            }
            else if(str.charAt(i) == '1'){
                Odd_count++;
            }
        }

        arr[0] = Even_count;
        arr[1] = Odd_count;

        return arr;
    }
}

Explain:

nope.

Complexity: