码迷,mamicode.com
首页 > 其他好文 > 详细

476. Number Complement【位运算】

时间:2017-03-27 00:28:27      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:rate   ati   返回   运算   循环   lin   amp   ica   tput   

2017/3/14 15:36:44


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.
 
解法1  
思路:5的二进制  00000101 ,   取反后  11111010   , 应该返回  00000010,从左至右遇到第一个0截止,切前面的1替换为0即为答案。
 
  1. publicclassSolution{
  2. publicint findComplement(int num){
  3. num =~num;
  4. int flag =31;
  5. while((1<<flag & num)!=0){
  6. --flag;
  7. }
  8. int comparer =1<<flag;
  9. comparer |= comparer>>1;
  10. comparer |= comparer>>2;
  11. comparer |= comparer>>4;
  12. comparer |= comparer>>8;
  13. comparer |= comparer>>16;
  14. return comparer & num ;
  15. }
  16. }
 
鉴于jdk中Integer类中有一个highestOneBit函数如下  ,作用   00010011---> 00010000 ,可以简化解法1的while循环
  1. publicstaticint highestOneBit(int i){
  2. // HD, Figure 3-1
  3. i |=(i >>1);
  4. i |=(i >>2);
  5. i |=(i >>4);
  6. i |=(i >>8);
  7. i |=(i >>16);
  8. return i -(i >>>1);
  9. }
顺便,了解了源码中如何得到最后一个1,作用  00001100  --> 00000100  函数如下
  1. publicstaticint lowestOneBit(int i){
  2. // HD, Section 2-1
  3. return i &-i;
  4. }
 
另 00001000 --> 00001111  , 在只有一个1的情况下填充1 有个更简单的方法,num<<1 - 1 。因此可以简化解法1的5个或位运算,得到解法2。
 
解法2:(借鉴discuss)
  1. publicclassSolution{
  2. publicint findComplement(int num){
  3. return~num &((Integer.highestOneBit(num)<<1)-1);
  4. }
  5. }
 
又 因为 num取反后 11111010, 所以不需要 00000111,只需要00000011即可,因此不用左移1位,这是比较多余的一步。
  1. publicclassSolution{
  2. publicint findComplement(int num){
  3. return~num &(Integer.highestOneBit(num)-1);
  4. }
  5. }
 

476. Number Complement【位运算】

标签:rate   ati   返回   运算   循环   lin   amp   ica   tput   

原文地址:http://www.cnblogs.com/flyfatty/p/6624792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!