IPA IP 2024 Question 85

A question IPA Japan published in 令和6年度 ITパスポート試験 公開問題 問85, translated into English. ITPEC is based on the same exams.

The function binaryToInteger receives, as the argument binaryStr, a value that represents an unsigned binary number of one or more digits as a character string, and returns the result of converting the value into an integer as the return value. For example, when it receives “100” as the argument, it returns 4. Which of the following is the appropriate combination of pieces of code to be inserted into A and B in the program?

[Program]
○ integer: binaryToInteger(string: binaryStr)
integer: integerNum, digitNum, exponent, i
integerNum ← 0
for (increase i from 1 to the number of characters in binaryStr by 1)
digitNum ← the value obtained by converting the i-th character from the end of binaryStr to integer type
// Example: The character “1” is converted to the integer value 1
exponent ← A
integerNum ← B
endfor
return integerNum
OptionAB

Explanation

A: 2 to the power of (i − 1), B: integerNum + digitNum × exponent — the i-th digit from the right of a binary number is worth 2i − 1, and the digits' values are added up.

The loop reads the digits from the end, so i = 1 is the rightmost digit, worth 20 = 1. Each pass adds that digit times its place value to the running total, which starts at 0. Tracing “100”:

idigitNumexponentintegerNum
1010
2020
3144

The function returns 4, as the question requires. Run for every binary string from 0 to 1023, only this combination returns the right value for all of them.

Answer (d)

Why not others:

  • •(a) and (c) — B multiplies the total, which starts at 0, so it stays 0 for every input; “100” returns 0
  • •(b) — A gives the place values 1, 3, 7, … instead of 1, 2, 4, …; “100” returns 7

Key rule: In a binary number the digit in position i from the right is worth 2i − 1; accumulate a sum with + from a start of 0, never with × from 0.

Algorithm and Programming · AI-written, may contain errors

This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.