LeetCode-Bitwise AND of Numbers Range-解题报告

转载 2015年07月08日 19:08:09

原题链接 https://leetcode.com/problems/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. 


返回m-n之间的数字做&操作的值


我是在网上看到的一个做法,由于是好久之间做的了,不记得是看的谁的了。


对于给定的m和n:

对m和n做移位操作,每次向后移动一位,并同时用offset记录移动了多少位,

如果m == n 表示前面的部分相同,辣么对它们做与操作必定是m或者n。

如果m != n 表面当前位存在不同的值,不同的值与起来必定是 1 & 0 = 0。

所以最终答案就是 移位后当m == n 时 ans = m << offset .

很巧妙有没有,很佩服。当时想了很多,越想越复杂,每次写到一半就发现是错的。。

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


相关文章推荐

[Leetcode] 201. Bitwise AND of Numbers Range 解题报告

题目: Given a range [m, n] where 0 For example, given the range [5, 7], you should return 4. ...

Leetcode 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 ...

Leetcode 201 Bitwise AND of Numbers Range 区间内整数按位与

给出一个区间 [m, n],其中0 <= m <= n <= 2147483647,即m,n都是非负整数,返回这个区间内所有整数的按位与结果,包括m和n在内.

leetcode 201:Bitwise AND of Numbers Range

Question:   Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all num...

LeetCode 201 Bitwise AND of Numbers Range

Given a range [m, n] where 0 For example, given the range [5, 7], you should return 4. 思路:介于(包括...

Leetcode 201 - Bitwise AND of Numbers Range(bit & math)

题意给定两个数m和n,并且m≤nm \leq n,求f(m, n) = m & (m + 1) & (m + 2) & ... & n的值。思路算法1我们知道,在范围[m,n][m, n]内,对于二进...
  • Lzedo
  • Lzedo
  • 2017-03-10 17:45
  • 105

Leetcode-201- Bitwise AND of Numbers Range

Given a range [m, n] where 0 For example, given the range [5, 7], you should return 4.  题意:m到n若干个数字...

leetCode191/201/202/136 -Number of 1 Bits/Bitwise AND of Numbers Range/Happy Number/Single Number

链接:https://leetcode.com/problems/number-of-1-bits/ 此题关键是如何判断一个数字的第i为是否为0  即: x& (1 class Solution { ...

[Leetcode] 327. Count of Range Sum 解题报告

题目: Given an integer array nums, return the number of range sums that lie in [lower, upper] i...

[leetcode] 327. Count of Range Sum 解题报告

题目链接: https://leetcode.com/problems/count-of-range-sum/ Given an integer array nums, return the...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)