These are the notes for C Coding Questions, episode 3, placement practice for people who finished the SyntaxPilot C course. Three number questions interviewers love because they look easy: reverse a number, palindrome number and sum of digits. Almost everyone gets the happy path right and misses the negative numbers and the overflow.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was compiled with gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, Linux x86-64, 32-bit int, 64-bit long long), the SyntaxPilot compiler's C command with warnings on, and every output below is real.
The one trick: % 10 and / 10
A cashier has a stack of notes with the digits of 1234 on them, the last digit, 4, on top.
| At the counter | In C | For 1234 |
|---|---|---|
| look at the top note | n % 10 (the remainder after dividing by 10) |
4 |
| take it off the stack | n / 10 (integer division: the fraction is dropped) |
123 |
% is the modulo operator: a % b is the remainder of a / b. Dividing two integers in C gives an integer, throwing away everything after the decimal point.
The digit loop, used by all three questions:
while (n > 0) {
int d = n % 10; /* last digit */
/* ... use d ... */
n = n / 10; /* drop it */
}
n |
d = n % 10 |
n / 10 |
|---|---|---|
| 1234 | 4 | 123 |
| 123 | 3 | 12 |
| 12 | 2 | 1 |
| 1 | 1 | 0 → stop |
Q1: Reverse a number
Problem. Read an int n and print its digits reversed, keeping the sign. If the reversed number does not fit in an int, print overflow.
| Input | Output |
|---|---|
1234 |
4321 |
-123 |
-321 |
1200 |
21 (leading zeros vanish) |
1534236469 |
overflow (9,646,324,351 > INT_MAX) |
0 |
0 |
Think out loud
Build the answer rev from 0: for each digit, shift rev one place left (× 10) and add the digit: 0 → 4 → 43 → 432 → 4321. Edge cases: 0, a negative number, a number ending in zeros, and a reverse too big for an int.
The obvious attempt
#include <stdio.h>
int main() {
int n, rev = 0;
scanf("%d", &n);
while (n > 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
printf("%d\n", rev);
return 0;
}
Input 1234:
4321
Input -123:
0
Input 1534236469:
1056389759
-123gives 0:while (n > 0)is false for a negative number, so the loop never runs.1534236469gives a number that isn't its reverse. The real reverse, 9,646,324,351, is far beyondINT_MAX(2,147,483,647, the largestint).rev * 10 + doverflowed, and overflow of a signedintis undefined behaviour (UB): the C standard promises nothing about the result. The value printed here is just what this build happened to produce. gcc gave no warning.
The fix
- Remember the sign and reverse the positive part.
- Work in
long long(at least 64 bits, up to about 9.22 × 10¹⁸), sox = -xcan't overflow even forINT_MIN, andrevcan't overflow for any 10-digit input. - Check the result against
INT_MINandINT_MAXfrom<limits.h>before printing it as an int.
A first version of the fix:
#include <stdio.h>
#include <limits.h>
int main() {
int n;
scanf("%d", &n);
long long x = n, rev = 0;
int sign = 1;
if (x < 0) {
sign = -1;
x = -x;
}
while (x > 0) {
rev = rev * 10 + x % 10;
x = x / 10;
}
rev = sign * rev;
if (rev > INT_MAX || rev < INT_MIN) printf("overflow\n");
else printf("%d\n", rev);
return 0;
}
The compiler message with -Wall:
main.c: In function ‘main’:
main.c:19:19: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long long int’ [-Wformat=]
19 | else printf("%d\n", rev);
| ~^ ~~~
| | |
| int long long int
| %lld
Input -123:
-321
The output is right, but -Wall caught a real bug: %d is for int, and rev is a long long. Passing the wrong type to a printf format is undefined behaviour too; on another platform it could print garbage. gcc even suggests the fix, %lld.
The final version:
#include <stdio.h>
#include <limits.h>
int main() {
int n;
scanf("%d", &n);
long long x = n, rev = 0;
int sign = 1;
if (x < 0) {
sign = -1;
x = -x;
}
while (x > 0) {
rev = rev * 10 + x % 10;
x = x / 10;
}
rev = sign * rev;
if (rev > INT_MAX || rev < INT_MIN) printf("overflow\n");
else printf("%lld\n", rev);
return 0;
}
All the test cases:
Input 1234:
4321
Input -123:
-321
Input 1200:
21
Input 1534236469:
overflow
Input 0:
0
Input -2147483648:
overflow
Input 2147483647:
overflow
-2147483648 (INT_MIN) reversed is -8,463,847,412, and 2147483647 reversed is 7,463,847,412: both too big, both detected.
Interview variant. If you may not use a wider type, check before each step: overflow happens exactly when
rev > (INT_MAX - d) / 10for positives (orrev < (INT_MIN - d) / 10for negatives, with C's%giving negative digits).
Complexity
One loop turn per digit. The number of digits d of n is about log₁₀ n (how many times you can divide by 10 before reaching 0): 1,000,000 has 7 digits. Time O(log n) (an int has at most 10 digits), space O(1).
Q2: Palindrome number
Problem. A palindrome reads the same forwards and backwards (level, 121, 1331). Read an int n and print palindrome or not a palindrome.
| Input | Output | Why |
|---|---|---|
121 |
palindrome | |
123 |
not a palindrome | 321 |
-121 |
not a palindrome | backwards it reads 121- |
10 |
not a palindrome | backwards 01 |
0, 7 |
palindrome | one digit |
2147447412 |
palindrome | near INT_MAX; the reverse is itself |
Think out loud
Reverse the number (Q1) and compare with the original. Negative numbers are never palindromes. Use long long for the reverse so a big input like 2147483647 (reverse 7,463,847,412) doesn't overflow.
The obvious attempt
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
long long rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
if (rev == n) printf("palindrome\n");
else printf("not a palindrome\n");
return 0;
}
Input 121:
not a palindrome
Input 7:
not a palindrome
Input 0:
palindrome
Every positive number is "not a palindrome"; only 0 passes.
Why it failed: the loop destroyed n
It's like doing your working on the only copy of a form: you erase one digit per step, and at the end the form says 0. After the loop n is 0, so rev == n really means rev == 0. Keep a copy before the loop.
The fix
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int original = n;
long long rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
if (original >= 0 && rev == original) printf("palindrome\n");
else printf("not a palindrome\n");
return 0;
}
All the test cases:
Input 121:
palindrome
Input 7:
palindrome
Input -121:
not a palindrome
Input 10:
not a palindrome
Input 0:
palindrome
Input 123:
not a palindrome
Input 2147447412:
palindrome
Input 2147483647:
not a palindrome
Interview variant. Reverse only half the digits: pop digits from
nintorevwhilen > rev, then comparen == rev || n == rev / 10. Numbers ending in 0 (except 0) are never palindromes. This never builds a number bigger than the input, so it needs no wider type.
Complexity: O(log n) time, O(1) space.
Q3: Sum of digits
Problem. Read an int n and print the sum of its digits. The minus sign is not a digit.
| Input | Output |
|---|---|
1234 |
10 |
-123 |
6 |
0 |
0 |
-2147483648 (INT_MIN) |
47 |
The obvious attempt
This one does let negative numbers into the loop (n != 0):
#include <stdio.h>
int main() {
int n, sum = 0;
scanf("%d", &n);
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
printf("%d\n", sum);
return 0;
}
Input 1234:
10
Input -123:
-6
A sum of digits can't be -6.
Why: in C, % keeps the sign of the left operand
Since C99, integer division rounds toward zero, and the remainder has the sign of the left operand, so that (a / b) * b + a % b == a always holds:
| Expression | Value |
|---|---|
-123 / 10 |
-12 |
-123 % 10 |
-3 (not 7) |
-47 / 10 |
-4 |
-47 % 10 |
-7 |
So the loop saw -3, -2, -1 and added up to -6.
The fix: sum the digits of the absolute value (the number without its sign). Careful: |INT_MIN| = 2,147,483,648 is one more than INT_MAX, so -n overflows an int for INT_MIN. Do it in a long long.
#include <stdio.h>
int main() {
int n, sum = 0;
scanf("%d", &n);
long long x = n;
if (x < 0) x = -x;
while (x != 0) {
sum = sum + x % 10;
x = x / 10;
}
printf("%d\n", sum);
return 0;
}
All the test cases:
Input -123:
6
Input 1234:
10
Input 0:
0
Input -2147483648:
47
Input 9:
9
Complexity: O(log n) time, O(1) space.
Complexity summary
| Question | Loop turns | Time | Extra space |
|---|---|---|---|
| Reverse a number | one per digit (≤ 10 for an int) | O(log n) | O(1) |
| Palindrome number | one per digit | O(log n) | O(1) |
| Sum of digits | one per digit | O(log n) | O(1) |
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
while (n > 0) with n = -123 |
no error: prints 0 | negatives skip the loop | save the sign, work on the absolute value |
int rev; rev = rev * 10 + d; |
no warning: a wrong number (undefined behaviour) | the reverse is bigger than INT_MAX |
build in long long, check INT_MIN..INT_MAX |
printf("%d\n", rev); with long long rev |
warning: format '%d' expects argument of type 'int', but argument 2 has type 'long long int' [-Wformat=] |
the format doesn't match the type | %lld |
if (rev == n) after the loop |
no error: 121 is "not a palindrome" | the loop made n 0 |
int original = n; before the loop |
sum += n % 10; with n = -123 |
no error: -6 | -123 % 10 == -3 in C |
sum the digits of |
n = -n; for INT_MIN |
undefined behaviour | 2,147,483,648 doesn't fit in an int |
long long x = n; x = -x; |
while (n != 0) count++ for counting digits |
0 digits for n = 0 |
the loop never runs | do { ... } while (x != 0); |
Your turn: count the digits (solution)
Problem. Read an int n and print how many digits it has. 12345 → 5, -908 → 3, 0 → 1.
The trap. 0 has one digit, but while (n != 0) runs zero times. A do-while loop runs its body once before checking the condition.
Show the solution
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
long long x = n;
if (x < 0) x = -x;
int count = 0;
do {
count++;
x = x / 10;
} while (x != 0);
printf("%d\n", count);
return 0;
}
Input 12345:
5
Input -908:
3
Input 0:
1
Input -2147483648:
10
Time O(log n), space O(1).
Practice questions (with solutions)
1. Product of the digits of n.
Solution
long long because ten digits of 9 would give 9¹⁰ = 3,486,784,401, more than INT_MAX.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
long long x = n, product = 1;
if (x < 0) x = -x;
do {
product = product * (x % 10);
x = x / 10;
} while (x != 0);
printf("%lld\n", product);
return 0;
}
Input 12345:
120
Input -908:
0
Input 0:
0
2. The largest digit of n.
Solution
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
long long x = n;
if (x < 0) x = -x;
int best = 0;
do {
int d = x % 10;
if (d > best) best = d;
x = x / 10;
} while (x != 0);
printf("%d\n", best);
return 0;
}
Input 12345:
5
Input -908:
9
Input 0:
0
3. Is the reverse of n a prime? Do this after episode 4 (prime check): reverse with Q1, then test the result for primality.
Quick quiz
int n = -47;
printf("%d %d\n", n % 10, n / 10);
(A) -7 -4 (B) 3 -5 (C) 7 4 (D) -7 -5
Answer
(A) -7 -4. Division rounds toward zero (-4.7 → -4), and the remainder keeps the sign of the left operand (-7). Check: -4 × 10 + (-7) = -47.
Interview questions
- How do you get the last digit of a number, and remove it?
n % 10andn / 10. - What is
-7 % 3in C? -1: the remainder takes the sign of the left operand (C99 and later). - How do you detect overflow when reversing an int? Build the reverse in a wider type and compare with
INT_MIN/INT_MAX, or, without a wider type, checkrev > (INT_MAX - d) / 10before each step. - Why is signed overflow dangerous? It's undefined behaviour: the compiler assumes it never happens and may produce any result.
- Why can't you write
abs(INT_MIN)? Its absolute value isINT_MAX + 1, which doesn't fit in anint(undefined behaviour). Convert tolong longfirst. - Is -121 a palindrome? No: reversed it reads
121-. - What is the time complexity of digit problems? O(log n): one step per digit.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Digit | One of the symbols 0 to 9 in a number | 1234 has digits 1, 2, 3, 4 |
Modulo operator % |
The remainder after integer division | 1234 % 10 == 4 |
| Integer division | Dividing two integers; the fraction is dropped (rounded toward zero) | 1234 / 10 == 123, -123 / 10 == -12 |
| Remainder | What is left after dividing | 7 divided by 3 leaves 1 |
| Reverse of a number | The digits in the opposite order | 1234 → 4321 |
| Palindrome | Reads the same forwards and backwards | 121, level |
| Absolute value | A number without its sign | |
| Sign | Whether a number is positive or negative | -123 is negative |
INT_MAX / INT_MIN |
The largest / smallest int: 2,147,483,647 / -2,147,483,648 |
from <limits.h> |
long long |
An integer type of at least 64 bits, up to about 9.22 × 10¹⁸ | long long rev = 0; |
| Integer overflow | A result too big (or too small) for its type | reversing 1534236469 in an int |
| Undefined behaviour (UB) | Code whose result the C standard doesn't define | signed overflow, %d with a long long |
-Wall |
gcc option that turns on the common warnings | catches %d vs %lld |
| Format specifier | The % code that tells printf the argument's type |
%d int, %lld long long |
do-while loop |
A loop that runs its body once before checking the condition | counting the digits of 0 |
| Logarithm (log₁₀ n) | How many times you can divide n by 10 before reaching 1 | log₁₀ 1000 = 3 |
| Edge case | An input at the boundary | 0, negatives, INT_MIN |
| Time complexity | How the work grows with the input | O(log n) |
| Space complexity | How the extra memory grows with the input | O(1) |
Summary
n % 10is the last digit,n / 10drops it; loop until the number is 0.- Reverse:
rev = rev * 10 + d; keep the sign; build inlong longand checkINT_MIN..INT_MAX. - Match
printfformats to types (%lldforlong long);-Wallcatches the mismatch. - Palindrome: save
originalbefore the loop that destroysn; negatives are never palindromes. - In C,
-123 % 10 == -3: work on the absolute value, in along longbecause ofINT_MIN. - Digit questions take O(log n) time and O(1) space.
Next episode: Number questions II: prime check (why up to √n), all primes up to n (Sieve of Eratosthenes), Armstrong numbers.