These are the notes for JavaScript Coding Questions, episode 1, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Three number questions that look easy: reverse a number, palindrome number and sum of digits. Almost everyone gets 123 right. The traps are in negative numbers, in JavaScript's division (it never drops the decimals) and in input that arrives as a string.
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 run with Node.js 24 (node main.js, v24.22.2), the SyntaxPilot compiler's JavaScript command. Programs that read standard input were run with the input piped in, for example printf '123\n9045\n-123\n0\n' | node main.js. Every output below is real.
The one trick: % 10 and Math.trunc(n / 10)
A cashier has a stack of notes with the digits of 1234 written on them, the last digit, 4, on top.
| At the counter | In JavaScript | For 1234 |
|---|---|---|
| a stack of notes: 1 2 3 4 | n = 1234 |
a number, digit by digit |
| look at the top note | n % 10 (the remainder after dividing by 10) |
4 |
| take it off the stack | Math.trunc(n / 10) (divide, then cut off the decimals) |
123 |
% is the remainder operator (people also call it modulo): a % b is what is left after dividing a by b. Math.trunc(x) removes everything after the decimal point (trunc is short for truncate, "cut off"): Math.trunc(123.4) is 123, Math.trunc(-12.3) is -12.
Why not just n / 10? Because JavaScript has one number type (a 64-bit floating-point number), so / never drops decimals: 1234 / 10 is 123.4, not 123. In C or Java, 1234 / 10 between two integers gives 123. Q1 shows what happens if you forget this.
The digit loop, used by all three questions:
while (n > 0) {
const d = n % 10; // last digit
// ... use d ...
n = Math.trunc(n / 10); // drop it
}
n |
d = n % 10 |
Math.trunc(n / 10) |
|---|---|---|
| 1234 | 4 | 123 |
| 123 | 3 | 12 |
| 12 | 2 | 1 |
| 1 | 1 | 0 → stop |
Q1: Reverse a number
Problem. Given an integer n, return its digits reversed, keeping the sign.
| Input | Output |
|---|---|
123 |
321 |
1200 |
21 (leading zeros vanish) |
7 |
7 |
0 |
0 |
-123 |
-321 |
Think out loud
Input: one integer. Output: a number (not a string), same sign. Build the answer rev from 0: for each digit, shift rev one place left (× 10) and add the digit: 0 → 3 → 32 → 321. Say the edge cases to the interviewer before you write any code: 0, a single digit, a number ending in zeros, and a negative number.
The obvious attempt: the string trick
Turn the number into a string, split it into characters, reverse the array, join it back, turn it into a number:
function reverse(n) {
return Number(String(n).split("").reverse().join(""));
}
for (const n of [123, 1200, 7, -123]) console.log(n, "->", reverse(n));
Output:
123 -> 321
1200 -> 21
7 -> 7
-123 -> NaN
Why: the minus sign is a character too
String(-123) is "-123"; its characters are -, 1, 2, 3. Reversed and joined, that is "321-", and Number("321-") is NaN ("Not a Number"): the string isn't a valid number. No error is thrown; the wrong value just flows on. Many interviewers also say "no string tricks, do it with maths".
The second attempt: the math way, with plain /
function reverse(n) {
let rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n = n / 10;
}
return rev;
}
console.log(reverse(123));
Output:
Infinity
Why: JavaScript has no integer division
123 / 10 is 12.3, then 1.23, then 0.123, ... n gets smaller and smaller but stays above 0, so the loop keeps going. Each round multiplies rev by 10 and adds a fractional "digit". The largest number JavaScript can hold is Number.MAX_VALUE, about 1.8 × 10³⁰⁸; past that, a number becomes Infinity.
Measured on this exact loop: rev became Infinity at round 309, and the loop only stopped after 326 rounds, when n got too tiny to store and became exactly 0. Infinity × 10 + anything is still Infinity, so Infinity is returned.
123 / 10 → 12.3 12.3 / 10 → 1.23 1.23 / 10 → 0.123
Number.MAX_VALUE → 1.7976931348623157e+308
Number.MAX_VALUE * 10 → Infinity
The fix
n = Math.trunc(n / 10): divide, then cut off the decimals.Math.sign(n)gives-1,0or1(Math.sign(-123)is-1). Remember the sign.Math.abs(n)is the absolute value (the number without its sign): reverse the positive part, then put the sign back.
function reverse(n) {
const sign = Math.sign(n);
n = Math.abs(n);
let rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n = Math.trunc(n / 10);
}
return sign * rev;
}
for (const n of [123, 1200, 7, 0, -123]) console.log(n, "->", reverse(n));
Output, all the test cases:
123 -> 321
1200 -> 21
7 -> 7
0 -> 0
-123 -> -321
Interview note. JavaScript numbers are exact only up to
Number.MAX_SAFE_INTEGER(9,007,199,254,740,991). For bigger inputs, useBigInt(episode 3 of this series), where/does drop the decimals.
Complexity
The loop runs once per digit. A number with d digits takes d steps: time O(d). Since d is about log₁₀ n (1,000,000 has 7 digits), people also write O(log n). Space O(1): three variables (sign, n, rev), however big the number is.
Q2: Palindrome number
Problem. A palindrome reads the same forwards and backwards, like the word madam. Given an integer n, return true if it is a palindrome number, else false.
| Input | Output | Why |
|---|---|---|
121 |
true |
|
123 |
false |
backwards 321 |
7 |
true |
one digit |
0 |
true |
one digit |
1221 |
true |
even number of digits |
10 |
false |
backwards 01 |
-121 |
false |
backwards 121- |
Think out loud
Reverse it with the digit loop from Q1 and compare the reverse with n. Edge cases: one digit, 0, numbers ending in 0, negatives.
The obvious attempt
function isPalindrome(n) {
let rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n = Math.trunc(n / 10);
}
return rev === n;
}
for (const n of [121, 123, 7]) console.log(n, isPalindrome(n));
Output:
121 false
123 false
7 false
Even 7, a single digit, is "not a palindrome".
Why: the loop destroyed n
The loop keeps dividing n until it is 0. So at return rev === n, n isn't 121 any more: it is 0, and we compared the reverse with 0. It's like doing your rough work on the only copy of a form: the original is gone. (Only isPalindrome(0) would say true.)
The fix
Save a copy called original before the loop and compare with that. A negative number is never a palindrome, so return false straight away.
function isPalindrome(n) {
if (n < 0) return false;
const original = n;
let rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n = Math.trunc(n / 10);
}
return rev === original;
}
for (const n of [121, 123, 7, 0, 1221, -121, 10]) console.log(n, isPalindrome(n));
Output, all the test cases:
121 true
123 false
7 true
0 true
1221 true
-121 false
10 false
Interview variant. Reverse only half the digits: move digits from
nintorevwhilen > rev, then checkn === rev || n === Math.trunc(rev / 10). Numbers ending in 0 (except 0 itself) are never palindromes, so reject them first.
Complexity: O(d) time, O(1) space, the same as the reverse.
Q3: Sum of digits (from standard input)
Problem. The way online coding tests give it: the numbers come from standard input (stdin), one per line. For each, print the sum of its digits. The minus sign is not a digit.
| Input line | Output |
|---|---|
123 |
6 (1 + 2 + 3) |
9045 |
18 |
-123 |
6 |
0 |
0 |
Input used for every run below (typed into the compiler's input box, or piped in):
123
9045
-123
0
Think out loud
Read all of stdin, split it into lines (as in episode 14 of the JavaScript course), and handle each line. Edge cases: 0, negatives, and the fact that everything read from input is a string.
The obvious attempt: add the characters
Each line is already made of digits, so loop over its characters and add them:
const lines = require("fs").readFileSync(0, "utf8").trim().split("\n");
for (const s of lines) {
let sum = 0;
for (const ch of s) sum += ch;
console.log(s, "->", sum);
}
Output:
123 -> 0123
9045 -> 09045
-123 -> 0-123
0 -> 00
Why: + joins strings
ch is a string ("1", "2", ...). 0 + "1" is not 1: when either side of + is a string, + does string concatenation (joins them), giving "01" (episode 3 of the course). So sum just glued the characters together behind the starting 0.
The second attempt: Number() and the digit loop
Turn each line into a number with Number(s) and use the digit loop. Loop while (n !== 0) so negatives get into the loop too:
function digitSum(n) {
let sum = 0;
while (n !== 0) {
sum += n % 10;
n = Math.trunc(n / 10);
}
return sum;
}
const lines = require("fs").readFileSync(0, "utf8").trim().split("\n");
for (const s of lines) console.log(s, "->", digitSum(Number(s)));
Output:
123 -> 6
9045 -> 18
-123 -> -6
0 -> 0
A sum of digits can't be -6.
Why: in JavaScript, % keeps the sign of the left side
% is a remainder, not a mathematical modulo: the result has the sign of the left operand.
| Expression | Value |
|---|---|
123 % 10 |
3 |
-123 % 10 |
-3 (not 7) |
-47 % 10 |
-7 |
Math.trunc(-47 / 10) |
-4 |
-7 % 3 |
-1 |
7 % -3 |
1 |
So the loop saw -3, -2, -1 and added them up to -6.
The fix
One line: n = Math.abs(n) before the loop, then the usual while (n > 0).
function digitSum(n) {
n = Math.abs(n);
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.trunc(n / 10);
}
return sum;
}
const lines = require("fs").readFileSync(0, "utf8").trim().split("\n");
for (const s of lines) console.log(s, "->", digitSum(Number(s)));
Output, all the test cases:
123 -> 6
9045 -> 18
-123 -> 6
0 -> 0
Complexity: O(d) time per number, O(1) space (not counting the lines array that holds the input).
Complexity summary
| Question | Loop turns | Time | Extra space |
|---|---|---|---|
| Reverse a number | one per digit | O(d) = O(log n) | O(1) |
| Palindrome number | one per digit | O(d) | O(1) |
| Sum of digits | one per digit, per line | O(d) per number | O(1) |
Common mistakes (and what you really see)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
Number(String(-123).split("").reverse().join("")) |
NaN (no error) |
the - is reversed too: "321-" |
Math.sign + Math.abs, or the digit loop |
n = n / 10 in the digit loop |
Infinity (326 rounds) |
JS has no integer division: 12.3, 1.23, ... | n = Math.trunc(n / 10) |
return rev === n after the loop |
false for 121 and even 7 |
the loop turned n into 0 |
const original = n; first |
sum += ch on input characters |
0123, 09045 |
input is a string; + joins strings |
Number(s) first |
summing n % 10 for n = -123 |
-6 |
-123 % 10 is -3 |
n = Math.abs(n) |
Math.floor(n / 10) on a negative n with while (n !== 0) |
-123 → -13 → -2 → -1 → -1 → -1 ... forever |
Math.floor(-0.1) is -1; floor rounds down, not toward 0 |
Math.trunc, on Math.abs(n) |
while (n > 0) count++ to count digits |
0 -> 0 |
the loop never runs for 0 | do { ... } while (n > 0) |
Mini project: a digit report
Read integers from stdin, one per line, and print a report for each: digit count, reverse, palindrome, digit sum. Lines that aren't integers are skipped (Number.isInteger is false for 12.5 and for NaN).
// Digit report: one integer per line from standard input.
function reverse(n) {
const sign = Math.sign(n);
n = Math.abs(n);
let rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n = Math.trunc(n / 10);
}
return sign * rev;
}
function isPalindrome(n) {
return n >= 0 && reverse(n) === n;
}
function digitSum(n) {
n = Math.abs(n);
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.trunc(n / 10);
}
return sum;
}
function countDigits(n) {
n = Math.abs(n);
let count = 0;
do {
count++;
n = Math.trunc(n / 10);
} while (n > 0);
return count;
}
const lines = require("fs").readFileSync(0, "utf8").trim().split("\n");
for (const s of lines) {
const n = Number(s);
if (!Number.isInteger(n)) {
console.log(`${s.trim()}: not an integer, skipped`);
continue;
}
console.log(`${n}: digits=${countDigits(n)} reverse=${reverse(n)} palindrome=${isPalindrome(n)} sum=${digitSum(n)}`);
}
Input:
123
9045
-123
0
121
12.5
abc
Output:
123: digits=3 reverse=321 palindrome=false sum=6
9045: digits=4 reverse=5409 palindrome=false sum=18
-123: digits=3 reverse=-321 palindrome=false sum=6
0: digits=1 reverse=0 palindrome=true sum=0
121: digits=3 reverse=121 palindrome=true sum=4
12.5: not an integer, skipped
abc: not an integer, skipped
Your turn: count the digits (solution)
Problem. Count how many digits n has, using the digit loop. 12345 → 5, -907 → 3, 0 → 1.
The trap. With while (n > 0), the loop never runs for 0, so it says 0 has 0 digits:
function countDigits(n) {
n = Math.abs(n);
let count = 0;
while (n > 0) {
count++;
n = Math.trunc(n / 10);
}
return count;
}
for (const n of [12345, -907, 0]) console.log(n, "->", countDigits(n));
12345 -> 5
-907 -> 3
0 -> 0
Show the solution
A do-while loop runs its body once before checking the condition, so 0 counts as one digit. Math.abs handles negatives (the minus sign isn't a digit).
function countDigits(n) {
n = Math.abs(n);
let count = 0;
do {
count++;
n = Math.trunc(n / 10);
} while (n > 0);
return count;
}
for (const n of [12345, -907, 0, 7, 1000]) console.log(n, "->", countDigits(n));
Output:
12345 -> 5
-907 -> 3
0 -> 1
7 -> 1
1000 -> 4
Time O(d), space O(1). (String(Math.abs(n)).length also works for integers, but the interviewer usually wants the loop.)
Practice questions (with solutions)
1. Product of the digits of n. 12345 → 120, -907 → 0, 0 → 0.
Solution
Start the product at 1 (not 0), and use do-while so that 0 gives 0.
function digitProduct(n) {
n = Math.abs(n);
let product = 1;
do {
product *= n % 10;
n = Math.trunc(n / 10);
} while (n > 0);
return product;
}
for (const n of [12345, -907, 0, 7, 999]) console.log(n, "->", digitProduct(n));
Output:
12345 -> 120
-907 -> 0
0 -> 0
7 -> 7
999 -> 729
Time O(d), space O(1).
2. Is n an Armstrong number? An Armstrong number with k digits equals the sum of each digit raised to the power k: 153 = 1³ + 5³ + 3³. (Full episode on this next time.)
Solution
Count the digits first (the "your turn" function), then add digit ** k with the digit loop. ** is the exponent operator. A copy m keeps n intact for the comparison (the Q2 lesson).
function countDigits(n) {
let count = 0;
do {
count++;
n = Math.trunc(n / 10);
} while (n > 0);
return count;
}
function isArmstrong(n) {
if (n < 0) return false;
const k = countDigits(n);
let sum = 0;
for (let m = n; m > 0; m = Math.trunc(m / 10)) {
sum += (m % 10) ** k;
}
return sum === n;
}
for (const n of [153, 370, 9474, 123, 0, 7, 10, -153]) console.log(n, isArmstrong(n));
Output:
153 true
370 true
9474 true
123 false
0 true
7 true
10 false
-153 false
Time O(d) (two passes over the digits), space O(1).
3. Reverse a number without Math.trunc. Use only % and -.
Solution
Subtract the last digit first, so n - d ends in 0 and dividing by 10 is exact: (123 - 3) / 10 is 12, with no decimals.
function reverse(n) {
const sign = Math.sign(n);
n = Math.abs(n);
let rev = 0;
while (n > 0) {
const d = n % 10;
rev = rev * 10 + d;
n = (n - d) / 10;
}
return sign * rev;
}
for (const n of [123, 1200, 7, 0, -123]) console.log(n, "->", reverse(n));
Output:
123 -> 321
1200 -> 21
7 -> 7
0 -> 0
-123 -> -321
Time O(d), space O(1).
4. The largest digit of n. Hint: keep best = 0 and update it with Math.max(best, n % 10) inside a do-while loop on Math.abs(n).
Quick quiz
What does this print?
let n = 47, s = 0;
while (n > 0) {
s = s * 10 + (n % 10);
n = Math.trunc(n / 10);
}
console.log(s + "1");
(A) 75 (B) 741 (C) 48 (D) NaN
Answer
(B) 741. The loop reverses 47 into the number 74. Then 74 + "1": one side is a string, so + joins them, giving the string "741". Real output:
741
Bonus quiz. What is -47 % 10 and Math.trunc(-47 / 10) in JavaScript?
Answer
-7 and -4 (real output: -7 -4). The remainder keeps the sign of the left side, and Math.trunc cuts toward 0. Check: -4 × 10 + (-7) = -47. (Math.floor(-47 / 10) would be -5.)
Interview questions
- How do you get the last digit of a number in JavaScript, and remove it?
n % 10gives it;Math.trunc(n / 10)removes it. Plainn / 10keeps the decimals. - Why does
Number(String(-123).split("").reverse().join(""))give NaN? The reversed string is"321-", which isn't a valid number. - Does JavaScript have integer division? Not for normal numbers:
7 / 2is3.5. UseMath.trunc(a / b)(orMath.floorfor non-negative values).BigIntdivision does drop the fraction:7n / 2nis3n. - What is
-7 % 3in JavaScript?-1:%is a remainder that takes the sign of the left operand. For a true modulo that is never negative, use((a % b) + b) % b. - What is the difference between
Math.truncandMath.floor? The same for positives; for negatives,trunccuts toward 0 (-12.3 → -12) andfloorgoes down (-12.3 → -13). - Is -121 a palindrome number? No: reversed it reads
121-. - Why does
0 + "1"give"01"? If either operand of+is a string,+concatenates. Convert input withNumber()(or unary+s) first. - How do you check for NaN?
Number.isNaN(x).NaN === NaNisfalse, because NaN is not equal to anything, even itself. - What is the time complexity of digit problems? O(d), one step per digit, which is O(log n). Space O(1).
- What if the number is bigger than
Number.MAX_SAFE_INTEGER? Digits are no longer exact; read it as a string, or useBigInt.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Digit | One of the symbols 0 to 9 in a number | 1234 has digits 1, 2, 3, 4 |
Remainder operator % (modulo) |
What is left after dividing; in JS it keeps the sign of the left side | 1234 % 10 is 4, -123 % 10 is -3 |
| Integer division | Division that drops the fraction; JS numbers don't have it | C: 123 / 10 == 12; JS: 123 / 10 is 12.3 |
Math.trunc(x) |
Cuts off everything after the decimal point (toward 0) | Math.trunc(12.3) → 12, Math.trunc(-12.3) → -12 |
Math.floor(x) |
Rounds down to the next whole number | Math.floor(-12.3) → -13 |
Math.sign(x) |
-1 for negatives, 0 for zero, 1 for positives | Math.sign(-123) → -1 |
Math.abs(x) |
Absolute value: the number without its sign | Math.abs(-123) → 123 |
| Absolute value | The size of a number, ignoring the sign | |-123| = 123 |
NaN |
"Not a Number": the result of a failed number conversion or calculation; its type is still number |
Number("321-") → NaN |
Number.isNaN(x) |
The reliable NaN test | Number.isNaN(NaN) → true |
Infinity |
The JS value for a number too big to hold | Number.MAX_VALUE * 10, 1 / 0 |
Number.MAX_VALUE |
The largest JS number, about 1.8 × 10³⁰⁸ | 1.7976931348623157e+308 |
Number.MAX_SAFE_INTEGER |
Largest integer JS stores exactly: 9,007,199,254,740,991 | beyond it, use BigInt |
Number(s) |
Converts a string to a number | Number("0123") → 123, Number("12a") → NaN |
Number.isInteger(x) |
true only for whole numbers | Number.isInteger(12.5) → false |
| Palindrome | Reads the same forwards and backwards | 121, 1221, madam |
| Reverse of a number | The digits in the opposite order | 1200 → 21 |
| Standard input (stdin) | The input stream a program reads; in the compiler, the input box | require("fs").readFileSync(0, "utf8") |
| String concatenation | Joining strings end to end; + does it when either side is a string |
0 + "1" → "01", 74 + "1" → "741" |
split / reverse / join |
String → array of characters, reverse the array, array → string | "123".split("") → ["1","2","3"] |
do-while loop |
A loop that runs its body once before checking the condition | counting the digits of 0 |
Exponent operator ** |
Raises to a power | 5 ** 3 → 125 |
| Edge case | An input at the boundary that often breaks code | 0, one digit, negatives, trailing zeros |
| Time complexity | How the number of steps grows with the input size | O(d) |
| Space complexity | How the extra memory grows with the input size | O(1) |
| Big-O notation | A way to write complexity, keeping only how it grows | O(1), O(d), O(n) |
| O(1) | Constant: the same amount however big the input | three variables |
| O(d) | Grows with the number of digits d | one loop turn per digit |
| O(log n) | Grows with the logarithm of n; for digits, d ≈ log₁₀ n | 1,000,000 has 7 digits |
| Logarithm (log₁₀ n) | How many times you can divide n by 10 before reaching 1 | log₁₀ 1000 = 3 |
Summary
n % 10is the last digit;Math.trunc(n / 10)drops it. Loop until the number is 0.- JavaScript's
/never drops decimals: plainn / 10in the loop ends inInfinity. - The string trick gives
NaNfor-123because the-gets reversed too. - Negatives: remember
Math.sign(n), work onMath.abs(n), put the sign back. - Palindrome: save
originalbefore the loop that destroysn; negatives are never palindromes. - Input is always a string: convert with
Number()before adding, or+concatenates ("0123"). - In JavaScript
-123 % 10is-3: useMath.absfirst. - Counting digits:
do-while, so 0 has one digit. - All three questions: O(d) time, O(1) space.
Next episode: Number questions II: prime check (why up to √n), the Sieve of Eratosthenes, Armstrong numbers.