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")- A. 1234 567
- B. -1234 -567
- C. -1234 567
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (counting trailing zeros in n factorial, via counting factors of 5)? (All variables…
- What will be the output of the following pseudocode (fast exponentiation)? (All variables are integers, so / is integer division.) Integer…
- What will be the output of the following pseudocode (checking if one string is a rotation of another)? Function isRotation(String a…
- What will be the output of the following pseudocode (counting total set bits across 1..n)? Function countSetBitsRange(Integer n) Integer…
- What will be the output of the following pseudocode (depth-first traversal of a graph given as an adjacency list)? Map graph = {0: [1, 2]…
- What will be the output of the following pseudocode (breadth-first traversal using a queue)? Map graph = {0: [1, 2], 1: [0, 3], 2: [0, 3]…