文档章节

476. Number Complement

初雪之音
 初雪之音
发布于 2017/02/28 20:57
字数 140
阅读 112
收藏 0

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:

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.

 

Code:

public class Solution {
    public int findComplement(int num) {
		int result = 0;

		if (num > 0) {
			int temp = ~0;
			while ((temp & num) != 0) {
				temp <<= 1;
			}
			result = ~temp & ~num;
		}

		return result;
	}
}

 

© 著作权归作者所有

共有 人打赏支持
初雪之音
粉丝 47
博文 268
码字总数 150009
作品 0
广州
程序员
私信 提问
Leetcode 476. Number Complement

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82666457 文章作者:Tyan 博客:noahsnail.com | CSDN | 简书 1. Descr...

SnailTyan
09/12
0
0
Calcc

Calcc 是一个基于命令行的32/64位数值计算工具。支持十六进制、十进制、八进制、二进制、BASE4、字符串、IPv4/6等输入输出格式。能进行的操作包括:complement, not, shift, rotate, xor, an...

匿名
2008/10/30
286
1
数的补数 Number Complement

问题: Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.(输出每个数的补码,实际上根据示例是要求实......

叶枫啦啦
2017/08/22
0
0
十进制转换为十六进制 Convert a Number to Hexadecimal

问题: Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal () must be in......

叶枫啦啦
2017/08/22
0
0
MIT Data Science Machine Becomes As Intuitive As Humans: Rise Of The Machines?

Researchers at MIT have developed a new artificial intelligence system that is able to outperform even the smartest human intuition in a number of different areas. The new big d......

Betty__
2016/10/12
2
0

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周六乱弹 —— 你一口我一口多咬一口是小狗

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @达尔文 :分享Roy Orbison的单曲《She's a Mystery to Me》 《She's a Mystery to Me》- Roy Orbison 手机党少年们想听歌,请使劲儿戳(这里...

小小编辑
今天
141
4
Spring源码学习笔记-1-Resource

打算补下基础,学习下Spring源码,参考书籍是《Spring源码深度解析》,使用版本是Spring 3.2.x,本来想试图用脑图记录的,发现代码部分不好贴,还是作罢,这里只大略记录下想法,不写太细了 ...

zypy333
今天
13
0
RestClientUtil和ConfigRestClientUtil区别说明

RestClientUtil directly executes the DSL defined in the code. ConfigRestClientUtil gets the DSL defined in the configuration file by the DSL name and executes it. RestClientUtil......

bboss
今天
21
0

中国龙-扬科
昨天
4
0
Linux系统设置全局的默认网络代理

更改全局配置文件/etc/profile all_proxy="all_proxy=socks://rahowviahva.ml:80/"ftp_proxy="ftp_proxy=http://rahowviahva.ml:80/"http_proxy="http_proxy=http://rahowviahva.ml:80/"......

临江仙卜算子
昨天
14
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部