Maychallenge (34) | Number Complement
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1:
Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- You could assume no leading zero bit in the integer’s binary representation.
- This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
5 mã nhị phân là 101 XOR 111 = 010. 8 mã nhị phân là 1000 XOR 1111 = 0111. 111 chính là 7 = 8 - 1 = 2^3 -1. 1111 chính là 15 = 2^4 - 1. Đến đây, ta chỉ cần biết độ dài bit của input để tạo mask XOR.
Độ dài của một số hệ 10 sang hệ 2 là : Log2(N). Vì Java chỉ có hàm log, nên dùng toán:
Như vậy là bài toán đã được giải quyết. Có một lưu ý là ban đầu mình tượng tại hàm pow của thư viện bị lỗi khi tính 2^32 lại ra 2147483647, nhưng thực ra đây là vấn đề tràn số. Khắc phục điều này bằng cách để kiểu long lớn hơn, chứ không cần viết hàm pow như mình.
Nhận xét
Đăng nhận xét