Question 31 --- What does the below given algorithm do?
Micron technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What does the below given algorithm do?
Note: strlen(covert) returns the length of covert]
Convert(num)
Input: A binary number of long data types
Output: ?
Convert(num)
numi <- 0
j <- 1
while (num != 0)
remainder <- num mod 10
numi <- numi + remainder * j
j <- j * 2
num <- num / 10
end while
write(numi)
Show answer & explanation
The algorithm extracts digits from right to left using mod 10 and division by 10, treating each digit as a binary digit and multiplying by powers of 2 (1, 2, 4, 8, ...). This is the classic binary-to-decimal conversion method. For example, binary 1011 is processed as: 1×1 + 1×2 + 0×4 + 1×8 = 11 in decimal.
Step-by-step Derivation:
Trace with binary input 1011 (which equals 11 in decimal):
- Iteration 1: remainder=1, numi=0+1×1=1, j=2, num=101
- Iteration 2: remainder=1, numi=1+1×2=3, j=4, num=10
- Iteration 3: remainder=0, numi=3+0×4=3, j=8, num=1
- Iteration 4: remainder=1, numi=3+1×8=11, j=16, num=0
- Loop ends, output: 11
The pattern: extracting binary digits and summing (digit × power_of_2) is the definition of binary-to-decimal conversion.