LeetCode 2595. Number of Even and Odd Bits

原题链接在这里:https://leetcode.com/problems/number-of-even-and-odd-bits/description/

题目:

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:

  • 1 <= n <= 1000

题解:

Have even and odd count, when n & cur != 0, accumulate the corresponding count.

Time Complexity: O(1). Since it is interger, it can't be more than 32 bits.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int[] evenOddBit(int n) {
 3         int even = 0;
 4         int odd = 0;
 5         int cur = 1;
 6         boolean isEven = true;
 7         while(cur <= n){
 8             if((n & cur) != 0){
 9                 if(isEven){
10                     even++;
11                 }else{
12                     odd++;
13                 }
14             }
15 
16             cur = cur << 1;
17             isEven = !isEven;
18         }
19 
20         return new int[]{even, odd};
21     }
22 }

 

posted @ 2024-05-16 11:14  Dylan_Java_NYC  阅读(7)  评论(0编辑  收藏  举报