zoukankan      html  css  js  c++  java
  • [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.

    分析:

    直接用"除二取余"的方法来获取二进制的值

    代码如下:(C#)

    public class Solution {
        public int HammingWeight(uint n) {
            int intResult = 0;
            uint intTemp = n;
            
            if(n<=1){
                return (int)n;
            }
    
            while(intTemp > 0){
                if(intTemp%2 ==1){
                    intResult++;
                }
                intTemp = intTemp/2;
            }
            
            return intResult;
        }
    }

    同样的思路用Java提交会报错,主要原因如下:

        - 输入值n可能为负数(但应视其为无符号整数,但Java中实际上是没有无符号整数的)

    所以采用:无符号右移操作,可以忽略符号位。

    代码如下(Java):

    public class Solution {
      public int hammingWeight(int n) {
            int ans = 0;
            while (n != 0) {
                ans += n & 1;
                n >>>= 1;
            }
            return ans;
        }
    }
  • 相关阅读:
    for循环
    3.9 作业
    while循环
    深浅拷贝
    条件与判断
    可变与不可变
    与用户交互与运算符
    垃圾回收机制
    【AC自动机】文本生成器
    【AC自动机】最短母串
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4803204.html
Copyright © 2011-2022 走看看