Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range.
Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range.
def atoi(s):
s = s.lstrip(); sign, i, n = 1, 0, 0
if s[:1] in '+-' and s: sign = -1 if s[0] == '-' else 1; i = 1
while i < len(s) and s[i].isdigit():
n = n * 10 + int(s[i]); i += 1
return max(-2**31, min(2**31 - 1, sign * n))
print(atoi(" -42abc"), atoi("4193 with words"), atoi("words 987"), atoi("-91283472332"))What is printed?- A. -42 4193 987 -2147483648
- B. 42 4193 0 -2147483648
- C. -42 4193 0 -2147483648
- D. -42 4193 0 -91283472332
Correct answer: C. -42 4193 0 -2147483648
Parsing stops at the first non-digit; text before any digit gives 0 ("words 987" → 0). Values beyond 32 bits are clamped to INT_MIN / INT_MAX. In C++/Java the overflow check must happen before n·10 + d. O(n).
More Coding Interview Problems questions
- Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7. java static long ways3(int n) { long MOD =…
- Problem: A frog jumps from stone 0 to stone n − 1; jumping from i to j (j ≤ i + k) costs |h[i] − h[j]|. Find the minimum cost. python def…
- Problem: Count palindromic substrings (each occurrence counts separately). python def countpal(s): n, c = len(s), 0 for center in range(2…
- Problem: Find the length of the longest arithmetic subsequence. python def longestap(a): dp = [{} for in a]; best = 1 for i in…
- Problem: Length of the longest strictly increasing subsequence with the O(n²) DP. cpp int lis(vector<int>& a) { vector<int> dp(a.size()…
- Problem: A hash table keyed by short strings uses Java's String.hashCode. Why do some keys collide? java // String.hashCode: h = 31h + c…