-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path1611-minimum-one-bit-operations-to-make-integers-zero.rb
55 lines (47 loc) · 1.5 KB
/
1611-minimum-one-bit-operations-to-make-integers-zero.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
51
52
53
54
55
# frozen_string_literal: true
# 1611. Minimum One Bit Operations to Make Integers Zero
# Hard
# https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero
=begin
Given an integer n, you must transform it into 0 using the following operations any number of times:
* Change the rightmost (0th) bit in the binary representation of n.
* Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 2:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Constraints:
0 <= n <= 109
=end
# @param {Integer} n
# @return {Integer}
def minimum_one_bit_operations(n)
result = 0
temp = n
while temp != 0
result ^= temp
temp = temp / 2
end
result
end
# **************** #
# TEST #
# **************** #
require "test/unit"
class Test_minimum_one_bit_operations < Test::Unit::TestCase
def test_
assert_equal 2, minimum_one_bit_operations(3)
assert_equal 4, minimum_one_bit_operations(6)
end
end