Web Log of Ross Chapman

Web Log of Ross Chapman

Byzantine algorithm studies: Using math to reverse an integer

Making code do something requires exactness but that doesn’t necessarily mean programmers will express grammars with any particular concision or ease. Code is an outcome of social construction, background, perhaps aesthetic desire. Toy code problems reveal the apparatus, for sure. If you ask me to reverse an integer I’ll build a world of arrays – because I like them. Directionality makes me think of traversal, therefore arrays. I also recall the reverse() convenience immediately. However, as a result, I’m forced to deploy morphological contortions; which might feel icky for someone derived within an algorithmic hermitage, auto-recursively deriving pleasure therein.

function reverseInt(int) { // STEP 1 - morph let intAsArrayOfStrings = int.toString().split(""); }

Reversal is now nearby:

function reverseInt(int) { // let intAsArrayOfChars = int.toString().split('') // STEP 2 - traverse, recombine let reversedIntString = intAsArrayOfStrings.reverse().join(""); }

All that remains is a second transmogrification back to the initial type and signing:

function reverseInt(int) { // let intAsArrayOfChars = int.toString().split('') // let reversedIntString = intAsArrayOfChars.reverse().join('') // STEP 3 - Sign let result = Number(reversedIntString) * Math.sign(num); }

But it has come to my attention that a mathy person prefers preservation, whereby the input is arithmetically recombinated with the help of division and multiplication.

function reverseInt(int) { let remainder = 0; let result = 0; while (int) { remainder = int % 10; result = result * 10 + remainder; int = parseInt(int / 10); } return result; } reverseInt(12345);

But there’s no translation from integer to array. No shift. Grammar school level maths instead. I guess this solution exalts type consistency. Perhaps belies an obsession with 10? The base binary pair. I can’t imagine the benefit of doing that in a commercial software project so it could only be an academic fancy, benchmarked under extreme conditions. It’s really clever, though.

Also, been thinking about slice a lot today. Never stop dreaming:

let int = 12345; let intAsStr = int.toString(); new Array(intAsStr.length) .fill(null) .map((_, idx) => intAsStr.slice(-(idx + 1))[0]) .join("");