[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][N
T S S N
_If_0_jump_to_Label_PRINT][S S S T S N
_Push_2][T S T S _Integer_division][S N
T _Swap_top_two][S S S T N
_Push_1][T S S S _Add][S N
T _Swap_top_two][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_top][T N
S T _Print_integer]
Letters S
(space), T
(tab), and N
(new-line) added as highlighting only.
[..._some_action]
added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
Integer i = STDIN as integer
Integer r = 0
Start LOOP:
if i is 0:
Call function PRINT_AND_EXIT
i = i integer-divided by 2
r = r + 1
Go to next iteration of LOOP
function PRINT_AND_EXIT:
Print r as integer
Exit with error
Example run (n=16
):
Command Explanation Stack HEAP STDIN STDOUT STDERR
SSSN Push 0 [0]
SNS Duplicate top (0) [0,0]
SNS Duplicate top (0) [0,0,0]
TNTT Read STDIN as integer [0,0] {0:16} 16
TTT Retrieve [0,16] {0:16}
NSSN Create Label_LOOP [0,16] {0:16}
SNS Duplicate top (16) [0,16,16] {0:16}
NTSSN If 0: Jump to Label_PRINT [0,16] {0:16}
SSSTSN Push 2 [0,16,2] {0:16}
TSTS Integer-divide (16/2) [0,8] {0:16}
SNT Swap top two [8,0] {0:16}
SSSTN Push 1 [8,0,1] {0:16}
TSSS Add (0+1) [8,1] {0:16}
SNT Swap top two [1,8] {0:16}
NSNN Jump to Label_LOOP [1,8] {0:16}
SNS Duplicate top (8) [1,8,8] {0:16}
NTSSN If 0: Jump to Label_PRINT [1,8] {0:16}
SSSTSN Push 2 [1,8,2] {0:16}
TSTS Integer-divide (8/2) [1,4] {0:16}
SNT Swap top two [4,1] {0:16}
SSSTN Push 1 [4,1,1] {0:16}
TSSS Add (1+1) [4,2] {0:16}
SNT Swap top two [2,4] {0:16}
NSNN Jump to Label_LOOP [2,4] {0:16}
SNS Duplicate top (4) [2,4,4] {0:16}
NTSSN If 0: Jump to Label_PRINT [2,4] {0:16}
SSSTSN Push 2 [2,4,2] {0:16}
TSTS Integer-divide (4/2) [2,2] {0:16}
SNT Swap top two [2,2] {0:16}
SSSTN Push 1 [2,2,1] {0:16}
TSSS Add (2+1) [2,3] {0:16}
SNT Swap top two [3,2] {0:16}
NSNN Jump to Label_LOOP [3,2] {0:16}
SNS Duplicate top (2) [3,2,2] {0:16}
NTSSN If 0: Jump to Label_PRINT [3,2] {0:16}
SSSTSN Push 2 [3,2,2] {0:16}
TSTS Integer-divide (2/2) [3,1] {0:16}
SNT Swap top two [1,3] {0:16}
SSSTN Push 1 [1,3,1] {0:16}
TSSS Add (3+1) [1,4] {0:16}
SNT Swap top two [4,1] {0:16}
NSNN Jump to Label_LOOP [4,1] {0:16}
SNS Duplicate top (1) [4,1,1] {0:16}
NTSSN If 0: Jump to Label_PRINT [4,1] {0:16}
SSSTSN Push 2 [4,1,2] {0:16}
TSTS Integer-divide (1/2) [4,0] {0:16}
SNT Swap top two [0,4] {0:16}
SSSTN Push 1 [0,4,1] {0:16}
TSSS Add (4+1) [0,5] {0:16}
SNT Swap top two [5,0] {0:16}
NSNN Jump to Label_LOOP [5,0] {0:16}
SNS Duplicate top (0) [5,0,0] {0:16}
NTSSN If 0: Jump to Label_PRINT [5,0] {0:16}
NSSSN Create Label_PRINT [5,0] {0:16}
SNN Discard top [5] {0:16}
TNST Print as integer [] {0:16} 5
error
Program stops with an error: No exit found.
floor(log2(num))+1
\$\endgroup\$num
is a power of two. \$\endgroup\$