博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode【191】Number of 1 Bits
阅读量:4133 次
发布时间:2019-05-25

本文共 786 字,大约阅读时间需要 2 分钟。

这道题的输入是一个无符号的整数

有两种办法

解法一、暴力解

把整数变成字符串,遍历字符串查找1的个数,注意,这里不能用String.valueOf

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        String str = Integer.toBinaryString(n);        int count = 0;        for(int i = 0; i < str.length();i++){            char a = str.charAt(i);            if(a == '1')                count++;        }        return count;    }}

解法二、位运算

用31个0和1个1和每一位做与操作,如果该位是1则结果为1,否则为0

与操作的规则是两个都是1则为1,否则为0

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int res = 0;        int mask = 1;        for(int i = 0; i < 32; i++){            if ((n & mask) != 0) {                res++;            }            mask<<=1;        }        return res;    }

 

转载地址:http://eejvi.baihongyu.com/

你可能感兴趣的文章
poj 1976 A Mini Locomotive (dp 二维01背包)
查看>>
db db2_monitorTool IBM Rational Performace Tester
查看>>
postgresql监控工具pgstatspack的安装及使用
查看>>
【JAVA数据结构】双向链表
查看>>
【JAVA数据结构】先进先出队列
查看>>
Objective-C 基础入门(一)
查看>>
Flutter Boost的router管理
查看>>
iOS开发支付集成之微信支付
查看>>
C++模板
查看>>
【C#】如何实现一个迭代器
查看>>
【C#】利用Conditional属性完成编译忽略
查看>>
VUe+webpack构建单页router应用(一)
查看>>
(python版)《剑指Offer》JZ01:二维数组中的查找
查看>>
Spring MVC中使用Thymeleaf模板引擎
查看>>
PHP 7 的五大新特性
查看>>
深入了解php底层机制
查看>>
PHP中的stdClass 【转】
查看>>
XHProf-php轻量级的性能分析工具
查看>>
OpenCV gpu模块样例注释:video_reader.cpp
查看>>
就在昨天,全球 42 亿 IPv4 地址宣告耗尽!
查看>>