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, Inclus Ive.
For example, given the range [5, 7], and you should return 4.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Has you met this question in a real interview? Idea: Find the law can, through analysis we found: 1, when m = N, directly return m or N. 2, when the length of the binary number representing m and n is unequal, the number of occurrences is bound to be 100 because the lower one is like a high one. 0, the length is a bit longer than the low number, this number and the length of the number is smaller than its "with", the result must be 0, 0 "and" any number is 0. That is, when the length of the binary number that represents m,n is inconsistent, the "and" operation is performed from M to N, the result is 0, and 3, when the length of the two is the same, the loop and operation can be done. Just note: When N is Int_max, special handling is required.
classsolution{ Public: intRangebitwiseand (intMintN) {intRET =m; intA = m, B =N; intLena =1, LenB =1; if(M = =N)returnm; while(A >>=1) Lena++; while(b >>=1) LenB++; if(Lena = =LenB) { for(inti = m +1; I <= N; i++) {ret&=i; if(i = =Int_max) Break; } } Elseret=0; returnret; }};
[Leetcode] Bitwise and of Numbers Range