Swap the first and last digits of a number in JavaScript
Beginner · 3 min read
Counting the digits in a number and moving digits around are classic practice exercises. They also turn up in real work: checking that a PIN or an account number has the right length, or reformatting a code. The simplest route is to turn the number into text, because text has a length and can be split into characters.
In this tutorial you will write digitCount(n), which counts the digits, and swapEnds(n), which swaps the first and last digit, so 1234 becomes 4231. You will also meet two edge cases that decide whether your answer is really finished: 1000 and 1e21. You need to know what a string, an array and a function are.
Numbers as text
String(n) turns a number into text. Text has a length, so counting digits looks like one step:
console.log(String(45678)); // 45678
console.log(String(45678).length); // 5
console.log(String(-1234).length); // 5
The last line is wrong: -1234 has four digits. The minus sign was counted as a character. Math.abs removes the sign first:
console.log(String(Math.abs(-1234)).length); // 4
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
60 Count the digits, then swap the outer two
easyCount how many digits a number has, then swap its first and last digit. Also exercise 29, which adds a number's digits; here they are counted and moved, and the string route has a different set of edges.
Stuck? Three hints, smallest first
- 1.
String(n).lengthcounts digits, once you have dealt with the minus sign. - 2. Swapping is easiest on an array of characters, then
joinback. - 3. Try both on
1000and on1e21before deciding you are finished.
Step 1: count the digits
The answer also uses Math.trunc, which drops any decimal part, so 12.5 is counted as the two digits of 12:
const digitCount = (n) => String(Math.abs(Math.trunc(n))).length;
console.log(digitCount(45678)); // 5
console.log(digitCount(-1234)); // 4
console.log(digitCount(0)); // 1
Zero has one digit, and String(0) is '0', so that works without any special case.
Step 2: swap two items in an array
To swap digits, split the text into an array of characters. JavaScript can swap two array items in one line with destructuring: the right side builds a new pair in the other order, and the left side unpacks it back into the two positions:
const digits = ['1', '2', '3', '4'];
[digits[0], digits[3]] = [digits[3], digits[0]];
console.log(digits.join('')); // 4231
Step 3: swapEnds
Put it together. The last position is digits.length - 1. After swapping, join the characters and turn the text back into a number:
function swapEnds(n) {
const digits = String(Math.abs(n)).split('');
const last = digits.length - 1;
[digits[0], digits[last]] = [digits[last], digits[0]];
return Number(digits.join('')) * Math.sign(n || 1);
}
console.log(swapEnds(1234)); // 4231
console.log(swapEnds(-1234)); // -4231
console.log(swapEnds(7)); // 7
Math.sign(n) is -1 for a negative number and 1 for a positive one, so multiplying puts the minus sign back. For n of 0, Math.sign would give 0, so n || 1 uses 1 instead. A single digit swaps with itself.
Step 4: the leading zero
Now try 1000:
function swapEnds(n) {
const digits = String(Math.abs(n)).split('');
const last = digits.length - 1;
[digits[0], digits[last]] = [digits[last], digits[0]];
return Number(digits.join('')) * Math.sign(n || 1);
}
console.log(swapEnds(1000)); // 1
console.log(Number('0001')); // 1
The swap gives the text '0001', and there is no number 0001: leading zeros vanish when text becomes a number. If the zeros matter, as they would for a PIN, return the text instead of a number.
Step 5: very large numbers
const digitCount = (n) => String(Math.abs(Math.trunc(n))).length;
console.log(String(1e21)); // 1e+21
console.log(digitCount(1e21)); // 5
1e21 means 1 followed by 21 zeros, so it has 22 digits. But from 10 to the power of 21 upwards, JavaScript writes numbers as text in this short "e" form, so the string route counts five characters.
Step 6: count with logarithms instead
Math.log10(n) answers "10 to what power gives n?". For 45678 that is about 4.66. Round it down and add 1, and you have the digit count, with no text involved:
const digitCountByLog = (n) => (n === 0 ? 1 : Math.floor(Math.log10(Math.abs(n))) + 1);
console.log(digitCountByLog(45678)); // 5
console.log(digitCountByLog(1e21)); // 22
console.log(Math.log10(0)); // -Infinity
This route handles 1e21, but it needs its own special case, because Math.log10(0) is -Infinity. Neither route is wrong. Each has an edge, and knowing which one you chose is the skill.
The full solution
The answer panel has digitCount, swapEnds and digitCountByLog, and prints the counts and swaps including 1000 and 1e21. The checks confirm the minus sign isn't counted, zero has one digit, and the leading zero is lost. Press Run to see the output.
const digitCount = (n) => String(Math.abs(Math.trunc(n))).length;
function swapEnds(n) {
const digits = String(Math.abs(n)).split('');
const last = digits.length - 1;
[digits[0], digits[last]] = [digits[last], digits[0]];
return Number(digits.join('')) * Math.sign(n || 1);
}
// The arithmetic route, for comparison. No strings involved.
const digitCountByLog = (n) => (n === 0 ? 1 : Math.floor(Math.log10(Math.abs(n))) + 1);
console.log('digits in 45678 ->', digitCount(45678));
console.log('digits in -1234 ->', digitCount(-1234));
console.log('swap 1234 ->', swapEnds(1234));
console.log('swap 1000 ->', swapEnds(1000), '<- the leading zero is gone');
console.log('digits in 1e21 ->', digitCount(1e21), '<- String(1e21) is "1e+21"');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('five digits', digitCount(45678), 5);
test('the minus sign is not a digit', digitCount(-1234), 4);
test('zero has one digit', digitCount(0), 1);
test('the log version agrees for ordinary numbers', digitCountByLog(45678), 5);
test('but log10(0) is not finite, hence the special case', Number.isFinite(Math.log10(0)), false);
test('swapping the ends', swapEnds(1234), 4231);
test('a leading zero cannot survive as a number', swapEnds(1000), 1);
test('very large numbers break the string route', digitCount(1e21), 5);
test('a single digit swaps with itself', swapEnds(7), 7);
Two edges decide whether this is correct. swapEnds(1000) should be 0001, and there is no such number — Number('0001') is 1. If the leading zero matters, the answer is text, not a number, and the function's return type has to change.
String(1e21) is "1e+21", so any digit-counting built on string length starts lying at 10²¹. Math.log10 avoids that but needs its own special case, since log10(0) is -Infinity. Neither route is wrong; each has a documented edge, and knowing which one you have chosen is the skill.
Common mistakes
- Counting the minus sign.
String(-1234).lengthis 5. UseMath.absfirst. - Expecting leading zeros to survive.
Number('0001')is 1. Keep the result as text if the zeros matter. - Trusting string length for huge numbers. From
1e21up,String(n)uses the "e" form.
Try it yourself
- Write
swapEndsText(n)that returns'0001'for 1000 instead of the number 1. - Reverse all the digits of a number, so 1234 becomes 4321.
- Check that a 4-digit PIN entered as text, like
'0420', really has four digits and nothing else.