CodingEasy
Conditional digit sum function
Filed under Microsoft
Free read 1 of 3Confirm how digit count is defined for negative sums (typically based on absolute value).
The question
Complete a function taking two integers x and y, returning x + y if the number of digits in the integer (x + y) equals x, otherwise returning x.
Constraints
- x and y are standard 32-bit integers.
- x can be negative or zero.
Examples
- Input
- x = 2, y = 8
- Output
- 10
- Why
- x + y = 10, which has 2 digits. Since 2 equals x, return 10.
- Input
- x = 3, y = 5
- Output
- 3
- Why
- x + y = 8, which has 1 digit. Since 1 does not equal x, return x (3).
Approach
Confirm how digit count is defined for negative sums (typically based on absolute value).
Convert x+y to string, count characters (handling minus sign), compare length with x, and return accordingly.
Compute sum s = x + y, count its digits using math (log10) or string length of abs(s), and compare to x.
Negative x or sums resulting in zero.
Solution
O(1) time, O(1) space
def conditional_sum(x: int, y: int) -> int:
total = x + y
digit_count = len(str(abs(total)))
return total if digit_count == x else x
Tips
- What they are testing: Test edge cases where x+y is zero, negative, or has varying digit counts.
- Common mistake: Forgetting that negative numbers might include a minus sign in string length calculations, so use absolute value for digit counting.
Related Microsoft questions
Collected from public candidate posts and coding forums. Updated Nov 2026.