Notice
Recent Posts
Recent Comments
Today
Total
01-11 01:45
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[LEETCODE] 191.Number of 1 Bits ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

[LEETCODE] 191.Number of 1 Bits

WonderJay 2022. 10. 10. 14:25
728x90
๋ฐ˜์‘ํ˜•
SMALL

https://leetcode.com/

TITLE : 191.Number of 1 Bits

Description : Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

 

2์ง„์ˆ˜๋กœ ๋‚˜ํƒ€๋ƒˆ์„ ๋•Œ, 1 ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

uint32_t n ์„ ์ž…๋ ฅ๋ฐ›์œผ๋ฉด, n ์ด 0์ด ์•„๋‹ ๋•Œ ๊นŒ์ง€ 1 ๊ณผ and operator ์„ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ ans ์— ๋ˆ„์ ํ•˜๊ณ  n ์„ right shift ํ•ด์„œ ๊ฐฑ์‹ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

ํ˜น์€ bitset ์„ ์ด์šฉํ•˜๋ฉด n bitset < 32 > (n).count(); ์œผ๋กœ ์‰ฝ๊ฒŒ ๊ตฌํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

 

 

[C++]

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ans = 0;
        while (n != 0) {
            ans += (n & 1);
            n = n >> 1;
        }
        return ans;
    }
};

 

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments