It’s Friday, so it’s time to get comfortable, weekend is coming 🙌, and for today we have a very easy JCC (JavaScript Coding Challenge)!
Here is another easy, and beautiful 😇 challenge from HackerRank:
Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. For instance, given the number
12
, its reverse is21
. Their difference is9
. The number120
reversed is21
, and their difference is99
.She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day.
Given a range of numbered days,
[i...j]
and a numberk
, determine the number of days in the range that are beautiful. Beautiful numbers are defined as numbers where|i - reverse(i)|
is evenly divisible byk
. If a day’s value is a beautiful number, it is a beautiful day. Print the number of beautiful days in the range.
Function Description
Create a
beautifulDays
function. It must return the number of beautiful days in the range.
beautifulDays
has the following parameters:
i
: the starting day numberj
: the ending day numberk
: the divisor
Isn’t this challenge beautiful? 😇
The solution
Let’s break the problem into smaller pieces. We’ll have to:
- Loop through all the numbers from
i
toj
- Get the difference between the number and its reverse
- Determine if the difference is evenly divisible by
k
Count
the beautiful numbers- Return the
count
function beautifulDays(i, j, k) {
let count = 0;
// Step 1.
for (let x = i; x <= j; x++) {
// Step 4.
if (isBeautifulDay(x, k)) {
count++;
}
}
// Step 5.
return count;
}
function isBeautifulDay(x, k) {
// Step 3.
return differenceOfReverse(x) % k === 0;
}
function differenceOfReverse(x) {
let reversedX = parseInt(
x
.toString()
.split('')
.reverse()
.join('')
);
// Step 2.
return Math.abs(x - reversedX);
}
I decided to split the solution in multiple functions. It’s easier to understand what’s going on this way.
Everything from the code above is pretty clear, but I do want to go over how we reverse the number.
Let’s work on an example number, let’s say: 120
. So we have: let x = 120;
.
Convert it to a string
x.toString(); // result: '120'
Split the string into an array of characters
x.toString().split(''); // result: ['1', '2', '0']
Reverse the array
x.toString()
.split('')
.reverse(); // result: ['0', '2', '1']
Join the characres from te array back to a string
x.toString()
.split('')
.reverse()
.join(''); // result: '021'
Convert the string back to a number
parseInt(
x
.toString()
.split('')
.reverse()
.join('')
); // result: 21
Voila! We have the reversed number!
Conclusion
Nothing fancy for today, but at the same time we had a chance to complete a challenge.
REMEMBER: even if you don’t work a lot in a day for your dream, it’s important to do something EVERY SINGLE DAY! Keep moving forward everyday even if it’s only a single small step! 😉 These small steps will pile up in something big one day!