181. Flip Bits【LintCode, by java】

本文介绍了一种计算两个32位整数间位翻转次数的方法,通过对比两个整数的二进制表示来确定需要改变的位数。提供了一个具体的Java实现示例。

Description

Determine the number of bits required to flip if you want to convert integer n to integer m.

Both n and m are 32-bit integers.

Example

Given n = 31 (11111), m = 14 (01110), return 2.

解题:比较两个整数对应的二进制数,共有多少位不同。注意,负数也包含在内。“>>>”在无符号右移,用0补齐。

 1 public class Solution {
 2     /**
 3      * @param a: An integer
 4      * @param b: An integer
 5      * @return: An integer
 6      */
 7     public int bitSwapRequired(int a, int b) {
 8         // write your code here
 9         int count = 0;  
10         for (int c = a ^ b; c != 0; c = c >>> 1) {
11             count += c & 1;
12         }
13         return count;
14     }
15 }

 

转载于:https://www.cnblogs.com/phdeblog/p/9200683.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值