There are some new tools to generate cool demos of short code snippets, one of these is wave snippets.
I put together a small demo of a very basic problem: write a function to reverse a positive integer.
Meaning take a number like 123 and make it 321. Got it?
I wrote this in typescript, and didn't handle a lot of extra stuff but it works for simple cases. Check it out:
Here is the finished code:
const reversePositiveInt = (toReverse: number):number => {
let source = toReverse
let accumulator = 0
while(true) {
if(source <= 0) {
break
}
const mod = source % 10
accumulator += mod
source = Math.floor(source / 10)
accumulator *= 10
}
return accumulator / 10
}
console.log(reversePositiveInt(12345))
// 54321
The method of doing is this is to shave off the last digit of the input number and put it at the front of a new integer one number at a time.
There is a way to do it faster, but written like this step by step I think it makes it easier to see what is going on.
Top comments (0)