- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0201-bitwise-and-of-numbers-range.rb
50 lines (41 loc) · 999 Bytes
/
0201-bitwise-and-of-numbers-range.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true
# 201. Bitwise AND of Numbers Range
# https://leetcode.com/problems/bitwise-and-of-numbers-range
# Medium
=begin
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
0 <= left <= right <= 231 - 1
=end
# @param {Integer} left
# @param {Integer} right
# @return {Integer}
defrange_bitwise_and(left,right)
shift=0
whileleft != right
left >>= 1
right >>= 1
shift += 1
end
left << shift
end
# **************** #
# TEST #
# **************** #
require"test/unit"
classTest_range_bitwise_and < Test::Unit::TestCase
deftest_
assert_equal4,range_bitwise_and(5,7)
assert_equal0,range_bitwise_and(0,0)
assert_equal0,range_bitwise_and(1,2147483647)
end
end