按位操作符只能用于整数基本数据类型中的单个bit中,操作符对应表格:

Operator Description
& 按位与(12345&1=1,可用于判断整数的奇偶性)
| 按位或
^ 异或(同假异真)
~ 非(一元操作符)
&=,|=,^= 合并运算和赋值
<<N 左移N位,低位补0
>>N 右移N位,(正数:高位补0,负数高位补1)
>>>N 无符号右移(无论正负数,高位皆补0)
<<=,>>=,>>>= 合并运算和赋值(移动相应位数再赋值给左边变量)

leetcode191:

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.

值得注意的是我们要将传入的int n作为无符号整数看待,但是在java中int是有符号的,我想到的方法就是利用上面的>>>无符号移位操作,代码如下:

public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int num = 0;
do{
if((n & 1) == 1) num++;
}while((n>>>=1) > 0);
return num;
} public static void main(String[] args){
System.out.println((new Solution()).hammingWeight(11));
}
}

leetcode190

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

二进制的倒置可以用移位来进行,增加运算效率

     public int reverseBits(int n) {
int rs = 0;
for (int i = 0; i < 32; i++) {
rs = (rs << 1) + (n & 1);
n >>= 1;
}
return rs;
}

leetcode7:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

十进制的倒置同样值得注意的就是倒置以后溢出的问题,我采用的方法就是函数内利用Long类型来进行计算,并在转换成int前与intMax进行比较,如果溢出返回0(题目要求)

     public int reverse(int x) {
long l = new Long(x);
Long tmp = 0L;
while (l != 0) {
tmp = tmp * 10 + l % 10L;
l /= 10;
}
if (x > 0 && tmp > 2147483647L || x < 0 && tmp < -2147483648)
return 0;
return tmp.intValue();
}

想到了新的解法再更新

最新文章

  1. js Form.elements[i]的使用实例
  2. 【Django】Django 如何支持 分组查询、统计?
  3. 用JavaScript操作Media Queries
  4. backbone前端基础框架搭建
  5. BA的广度和深度
  6. provider: Named Pipes Provider, error: 40 - 无法打开到 SQL Server 的连接
  7. C语言_基础代码_01
  8. Python中的浅拷贝与深拷贝
  9. Classy Numbers
  10. java笔记 -- 输入输出
  11. 2019swpuj2ee作业2--HTTP协议
  12. 【Spring】24、&lt;load-on-startup&gt;0&lt;/load-on-startup&gt;配置
  13. php解决前后端验证字符串长度不一致
  14. 【BZOJ1823】[JSOI2010]满汉全席(2-sat)
  15. vue-loader 作用
  16. zabbix监控Windows-server
  17. Centos下10000次循环测试php对Redis和共享内存(shm)读写效率
  18. P2522 [HAOI2011]Problem b
  19. HTTP权威指南读书笔记
  20. ECshop 迁移到 PHP7版本时遇到的兼容性问题,ecshopphp7

热门文章

  1. Odoo 二次开发教程(四)-只读、唯一性验证和ORM方法介绍
  2. C++哈夫曼树编码和译码的实现
  3. nodejs 模块恩仇录
  4. SQLServer存储过程事务用法
  5. for循环后面跟分号 - for (i = 0; i &lt;= 3; i++);这不是错误语句
  6. HDFS NameNode 设计实现解析
  7. 排列组合算法的javascript实现
  8. 最流行的编程语言 JavaScript 能做什么?
  9. UWP开发之控件:用WebView做聊天框
  10. EF:Oracle.DataAccess.Client.OracleException: ORA-12154: TNS:could not resolve the connect identifier specified