码迷,mamicode.com
首页 > 编程语言 > 详细

剑指offer-java

时间:2017-02-02 15:45:04      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:open   题意   面试官   取反   ges   indicator   sed   image   function   

leetcode 191. Number of 1 Bits 

题意:

Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011, so the function should return 3.

解法:

1.普通解法:利用1的移位相与

技术分享
 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         int flag = 1;
 5         int count = 0;
 6         while (flag != 0) {
 7             if ((n & flag) != 0) {
 8                 count++;
 9             }
10             flag = flag << 1;
11         }
12         return count;
13     }
14 }
View Code

2.能给面试官打来惊喜的解法,p80 利用减1的性质:减1其实是把最右边的一个1之后的位取反,再与原数字相与就只剩下了前面的位。

技术分享
 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         int count = 0;
 5         while (n != 0) {
 6             count++;
 7             n = n & (n - 1);
 8         }
 9         return count;
10     }
11 }
View Code

 

剑指offer-java

标签:open   题意   面试官   取反   ges   indicator   sed   image   function   

原文地址:http://www.cnblogs.com/fisherinbox/p/6361194.html

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