Description Given a binary array, find the maximum number of consecutive 1s in this array. 给定一个二进制数组,找出这个数组中最大的连续1的个数
public class Solution { public int findMaxConsecutiveOnes(int[] nums) { int maxNumber = 0,number = 0; int len = nums.length; //遇0则变0,遇1则加1 for(int i = 0;i < len; i++){ if(nums[i] == 0){ number = 0; } else{ number++; if(maxNumber < number) maxNumber = number; } } return maxNumber; }}public class Solution { public int findMaxConsecutiveOnes(int[] nums) { int maxNumber = 0,number = 0; int len = nums.length; //遇1则加1,遇0则变0 for(int i = 0;i < len; i++){ if(nums[i] == 1){ number ++; } else{ if(number > maxNumber){ maxNumber = number; } number = 0; } } //注意num[len - 1]如果是1的话没有执行给maxNumber赋值的语句 if(number >maxNumber){ maxNumber = number; } return maxNumber; }}Description The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 给定两个整数,求其对应二进制位上是不同数字的个数。
public int hammingDistance(int x, int y) { int distance = 0; int k = x ^ y; //调用Integer类中的bitcount方法求一个整数的二进制中1的个数 distance = Integer.bitCount(k); return distance; }public int hammingDistance(int x, int y) { int distance = 0; int k = x ^ y; System.out.PRintln(k); while(k != 0){ //和1相与,结果为1则最低位为1,结果为0则最低位为0 if( (k & 1) == 1) distance ++; k = k >> 1;//右移 } return distance;}//逐位异或public int hammingDistance(int x, int y) { int distance = 0; while(x !=0 || y!=0){ if(((x & 1) ^ (y & 1)) == 1){ distance ++; } x = x >> 1; y = y >> 1; } return distance; } //(借鉴)利用递归 public int hammingDistance(int x, int y) { if((x ^ y) == 0) return 0; return (x ^ y) % 2 + hammingDistance(x >> 1, y >> 1); }感想:1. 二进制位运算要充分利用二进制运算符,~,&,|,^(异或,相同为0,不同为1) 2. 巧妙利用递归简化代码
新闻热点
疑难解答