반응형
https://leetcode.com/problems/complement-of-base-10-integer/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
bit masking으로 해결한 문제였습니다.
📕 풀이방법
📔 풀이과정
n을 인자로 n의 bit를 반전하는 함수 get bit mask를 수행합니다. 이 함수는 n보다 크거나 작으며 모든 bit가 1인 mask를 만들어 반환해줍니다.
📔 정답 출력 | 반환
함수 결과와 n을 XOR한 결과를 반환합니다. 이는 같은 자리의 bit가 같으면 0을 다르면 1을 반환하는 연산자입니다.
📕 Code
📔 C++
class Solution {
public:
int getBitMask(int n) {
if(!n) return 1;
int mask = 1;
while(mask < n) {
mask = (mask << 1) | 1;
}
return mask;
}
int bitwiseComplement(int n) {
return n ^ getBitMask(n);
}
};
📔 Rust
impl Solution {
pub fn get_bit_mask(n: i32) -> i32 {
if n == 0 {
return 1;
}
let mut mask = 1;
while mask < n {
mask = (mask << 1) | 1;
}
return mask;
}
pub fn bitwise_complement(n: i32) -> i32 {
return n ^ Self::get_bit_mask(n);
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 1018. Binary Prefix Divisible By 5 (2) | 2023.10.05 |
---|---|
(C++, Rust) - LeetCode (easy) 1013. Partition Array Into Three Parts With Equal Sum (0) | 2023.10.04 |
(C++) - LeetCode (easy) 999. Available Captures for Rook (0) | 2023.09.22 |
(Python3) - LeetCode (easy) 989. Add to Array-Form of Integer (0) | 2023.09.18 |
(C++, Rust) - LeetCode (easy) 941. Valid Mountain Array (0) | 2023.09.11 |