LeetCode 算法题476 Number Complement

原题

2. Add Two Numbers

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

1
2
3
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:

1
2
3
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.

原题地址:https://leetcode.com/problems/number-complement/

思路

把int型输入转化为二进制字符串,然后根据字符串里每个字符是1还是0进行转换,最后再转为int型即可。

这个通过golang实现的话比较简单,熟悉基础库即可。

代码仅供参考。

代码实现

Golang实现

https://github.com/cook-coder/my-leetcode-solution/tree/master/easy/476

成绩

加载评论框需要科学上网