476:数字的补数

This commit is contained in:
huangge1199 2021-10-18 14:28:08 +08:00
parent 9f4d4e865a
commit ca5d8b298a
3 changed files with 113 additions and 1 deletions

View File

@ -0,0 +1,71 @@
//对整数的二进制表示取反0 1 1 0再转换为十进制表示可以得到这个整数的补数
//
//
// 例如整数 5 的二进制表示是 "101" 取反后得到 "010" 再转回十进制表示得到补数 2
//
//
// 给你一个整数 num 输出它的补数
//
//
//
//
//
//
// 示例 1
//
//
//输入num = 5
//输出2
//解释5 的二进制表示为 101没有前导零位其补数为 010所以你需要输出 2
//
//
// 示例 2
//
//
//输入num = 1
//输出0
//解释1 的二进制表示为 1没有前导零位其补数为 0所以你需要输出 0
//
//
//
//
// 提示
//
//
// 1 <= num < 2³¹
//
//
//
//
// 注意本题与 1009 https://leetcode-cn.com/problems/complement-of-base-10-integer/
//
// Related Topics 位运算 👍 256 👎 0
package leetcode.editor.cn;
//476:数字的补数
class NumberComplement {
public static void main(String[] args) {
//测试代码
Solution solution = new NumberComplement().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findComplement(int num) {
int highbit = 0;
for (int i = 1; i <= 30; ++i) {
if (num >= 1 << i) {
highbit = i;
} else {
break;
}
}
int mask = highbit == 30 ? 0x7fffffff : (1 << (highbit + 1)) - 1;
return num ^ mask;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,41 @@
<p>对整数的二进制表示取反(<code>0</code><code>1</code> <code>1</code><code>0</code>)后,再转换为十进制表示,可以得到这个整数的补数。</p>
<ul>
<li>例如,整数 <code>5</code> 的二进制表示是 <code>"101"</code> ,取反后得到 <code>"010"</code> ,再转回十进制表示得到补数 <code>2</code></li>
</ul>
<p>给你一个整数 <code>num</code> ,输出它的补数。</p>
<p>&nbsp;</p>
<ol>
</ol>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>num = 5
<strong>输出:</strong>2
<strong>解释:</strong>5 的二进制表示为 101没有前导零位其补数为 010。所以你需要输出 2 。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>num = 1
<strong>输出:</strong>0
<strong>解释:</strong>1 的二进制表示为 1没有前导零位其补数为 0。所以你需要输出 0 。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= num &lt; 2<sup>31</sup></code></li>
</ul>
<p>&nbsp;</p>
<p><strong>注意:</strong>本题与 1009 <a href="https://leetcode-cn.com/problems/complement-of-base-10-integer/">https://leetcode-cn.com/problems/complement-of-base-10-integer/</a> 相同</p>
<div><div>Related Topics</div><div><li>位运算</li></div></div><br><div><li>👍 256</li><li>👎 0</li></div>