191. Number of 1 Bits

Total Accepted: 87985 Total Submissions: 234407 Difficulty: Easy

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.

public class Solution {
// you need to treat n as an unsigned value   //使用按位与操作
public int hammingWeight(int n) {
int count = 0;
while(n!=0){
n = n&(n-1);
++count;
}
return count;
}
}

190. Reverse Bits

Total Accepted: 60957 Total Submissions: 208165 Difficulty: Easy

Reverse bits of a given 32 bits unsigned integer.

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

public class Solution {
// you need treat n as an unsigned value   //结果往右移,而n值往左移动,以此来匹配
public int reverseBits(int n) {
if(n==0)
return 0;
int result = 0;
for(int i=0;i<32;i++){
result <<= 1;
if((n&1)==1)
result++;
n >>= 1;
}
return result;
}
}

338. Counting Bits

Total Accepted: 17636 Total Submissions: 31865 Difficulty: Medium

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

    • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
    • Space complexity should be O(n).
    • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

使用动态规划的思想;

public class Solution {
public int[] countBits(int num) {
int[] arr = new int[num+1];
arr[0] = 0;
for(int i=1;i<=num;i++){
arr[i] = arr[i&(i-1)]+1;///数i中1的位数,与前面的i&(i-1)中1的位数有关,为i&(i-1)中1的位数+1;
}
return arr;
}
}

371. Sum of Two Integers

 

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3

不使用加减法对两数进行相加:

解题思路:使用位操作,异或(^)操作(进行不进位的加法),位与(&)操作进行标记待进位的位置,如a=5=0101,b=7=0111,不进位的加法的结果为a^b=0010,待进位的位置是a&b=0101,初次进位0101<<1=1010,与a^b进行相加又产生进位....如此循环,直到进位为0

public class Solution {
public int getSum(int a, int b) {
int sum = 0;
int carry = 0;
do{
sum = a^b;//相加不进位
carry = (a&b)<<1;//进位
a = sum;
b = carry;
}while(b!=0); return a;
}
}

201. Bitwise AND of Numbers Range

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

思路:使用n&(n-1),将n最右边的第一个位数为1的经过该操作后变为0,可减少很多运算;

  1)当n&(n-1)=0时,直接返回n=0;

  2)当n&(n-1)=m时,直接返回m;

  3)其他情况,n&(n-1)<m且不为0,最终的结果就是n&(n-1);

public class Solution {
public int rangeBitwiseAnd(int m, int n) {
while(n>m){
n = n&(n-1);
}
return n;
}
}
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int step = 0;
while(m!=n){
m >>= 1;
n >>= 1;
step ++;
}
return m<<step;
}
}

LeetCode之位操作题java的更多相关文章

  1. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  2. LeetCode第[1]题(Java):Two Sum 标签:Array

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  3. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  4. LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  5. LeetCode第[4]题(Java):Median of Two Sorted Arrays 标签:Array

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

  6. LeetCode第[29]题(Java):Divide Two Integers

    题目:两整数相除 难度:Medium 题目内容: Given two integers dividend and divisor, divide two integers without using ...

  7. LeetCode第[4]题(Java):Median of Two Sorted Arrays (俩已排序数组求中位数)——HARD

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

  8. LeetCode第[15]题(Java):3Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c  ...

  9. LeetCode第[16]题(Java):3Sum Closest 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, find three integers in S such that the sum is closes ...

随机推荐

  1. hadoop 的job.setOutputKeyClass和job.setOutputValueClass的几个问题

    昨天写了一个mapreduce函数一直有错误,找不到错误,今天找了一天终于解决了,原来是hadoop 的job.setOutputKeyClass和job.setOutputValueClas设置输出 ...

  2. mysql 查找除id外其他重复的字段数据

    如表 test1 有多个重复的字段 其中有些数据完全重复是错误的数据,我们要把他找出来,然后删除掉 select * from test1 a where (a.phone,a.name) in ( ...

  3. CentOS编译安装php7.2

    介绍: 久闻php7的速度以及性能那可是比php5系列的任何一版本都要快,具体性能有多好,建议还是先尝试下再说.如果你是升级或新安装,那你首先需要考虑php7和程序是否存在兼容性,如果程序是基于php ...

  4. 三分钟教你同步 Visual Studio Code 设置

      简介 Visual Studio Code(以下简称vsCode)现在已经渐渐成为前端开发的主力工具,谁让它这么轻便,功能又这么轻便呢.用vscode Coding的小伙伴们也一定会装很多插件吧. ...

  5. SpringBoot在logback.xml中读取application.properties中配置的日志路径

    1.在springboot项目中使用logback记录日志,在logback.xml中配置日志存储位置时读取application.properties中配置的路径,在 logback.xml中配置引 ...

  6. angualrJS(mvc)指令嵌套使用的一些问题

    angular的指令拥有一个独立作用域的概念. 一般定义指令的形式: define(['app'],function(mianapp){ mainapp.directive("tlmsAol ...

  7. 常见企业IT支撑【8、端口回流问题】

    端口回流故障场景,常见于内网启用了Server服务器,使用出口路由设备的外网口NAT映射了一个公网地址,域内内网主机访问了这个公网地址,访问不通. 故障容易出现在办公网内的带有对外Server测试环境 ...

  8. android 文件上传,中文utf-8编码

    要上传文件到后台的php服务器,服务器能收到中文,手机发送过去,却只能收到一堆转了UTF-8的编码(就是要decode后才是中文的编码).android这边上传文件通常是用stream方式上传的,用M ...

  9. jq 合并json对象

    一,保存object1和2合并后产生新对象,若2中有与1相同的key,默认2将会覆盖1的值 1 var object = $.extend({}, object1, object2); 二,将2的值合 ...

  10. Apache Ignite简介以及Ignite和Coherence、Gemfire、Redis等的比较

    一.Ignite简介 Apache Ignite 内存数组组织框架是一个高性能.集成和分布式的内存计算和事务平台,用于大规模的数据集处理,比传统的基于磁盘或闪存的技术具有更高的性能,同时他还为应用和不 ...