-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinteger_replacement
More file actions
58 lines (55 loc) · 1.3 KB
/
Copy pathinteger_replacement
File metadata and controls
58 lines (55 loc) · 1.3 KB
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
56
57
58
*&---------------------------------------------------------------------*
*& Report zinteger_replacement
*&---------------------------------------------------------------------*
* 397. Integer Replacement
*Given a positive integer n, you can apply one of the following operations:
*If n is even, replace n with n / 2.
*If n is odd, replace n with either n + 1 or n - 1.
*Return the minimum number of operations needed for n to become 1.
*
*Example 1:
*Input: n = 8
*Output: 3
*Explanation: 8 -> 4 -> 2 -> 1
*
*Example 2:
*Input: n = 7
*Output: 4
*Explanation: 7 -> 8 -> 4 -> 2 -> 1
*or 7 -> 6 -> 3 -> 2 -> 1
*
*Example 3:
*Input: n = 4
*Output: 2
*&---------------------------------------------------------------------*
REPORT zinteger_replacement.
DATA(counter) = 0.
DATA str TYPE string.
PARAMETERS input TYPE i.
IF input IS INITIAL OR input < 0.
DATA(result) = -1.
ENDIF.
CASE input.
WHEN 1.
result = input.
WHEN OTHERS.
WHILE ( input > 1 ).
DATA(i) = input.
WRITE:/ |{ input }|.
IF ( input MOD 2 = 0 ).
input = input / 2.
ELSE.
i = input + 1.
IF ( i MOD 4 = 0 ).
input = i.
ELSE.
input = i - 2.
ENDIF.
ENDIF.
counter += 1.
ENDWHILE.
ENDCASE.
result = counter.
Write:/ '1'.
ULINE.
WRITE:/ |Output:{ result }|.