ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (manually parsing a signed integer string)?

What will be the output of the following pseudocode (manually parsing a signed integer string)?
Function strToInt(String s)
    Integer sign = 1, i = 0
    if (s[0] == '-')
        sign = -1
        i = 1
    end if
    Integer n = 0
    while (i < length(s))
        n = n * 10 + digitValue(s[i])
        i = i + 1
    end while
    return sign * n
End Function

Print strToInt("-1234"), strToInt("567")
  1. A. 1234 567
  2. B. -1234 -567
  3. C. -1234 567
  4. D. 1234 -567

Correct answer: C. -1234 567

For '-1234', the sign flag is set and parsing starts from index 1, building 1234, then negated: -1234. For '567', no leading minus, so it parses straight to 567.

More Pseudocode and Code Tracing questions

Exams that ask this topic