IPA FE Subject B 2024 Question 2
A question IPA Japan published in 令和6年度 基本情報技術者試験 科目B 公開問題 問2, translated into English. ITPEC is based on the same exams.
From the answer group below, select the correct answer to be inserted into blank in the program.
The function convDecimal receives as an argument a string of one or more characters that consists only of “0” and “1”, and returns the integer value obtained by interpreting the string as an unsigned binary number. For example, when “10010” is given as an argument, 18 is returned.
The function int, which is used by the function convDecimal, returns the integer value 0 if the character given as an argument is “0”, and returns the integer value 1 if it is “1”.
Answer group
Explanation
result × 2 + int(the i-th character of binary) — reading the digits from the left, each step shifts the value so far one binary place up (doubles it) and adds the next digit.
This is Horner's method: 100102 = (((1 × 2 + 0) × 2 + 0) × 2 + 1) × 2 + 0. The loop runs i from 1 to length, so the i-th character is the digits in order from the most significant one, and the doubling must come before the new digit is added. Trace of convDecimal(:
It returns 18, as the question says.
Answer (d)
Why not others:
- •(a) and (b) — never double
result, so they only count the 1s: “10010” gives 2 - •(c) — doubles correctly but takes the characters from the right, the least significant first, so the first digit read ends up with the highest weight: the value of the reversed string, 9 (01001) for “
10010”
Key rule: To convert a digit string to a number from the left, multiply the running value by the base and add the next digit; going from the right, you must instead multiply each digit by a growing place value.
Math & Numbers · 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.