Categories
algorithms kotlin

Problem 5.4 from EPI -> Closest integer with the same weight

This seems like a greedy problem but its quite simple. Look at a place where you can swap 1 and 0 in the given number, the right most the location is the smaller difference will be, that is why the right most is called the least significant bit. So go from right to left and the moment you encounter two bits that differ swap them, take a look at a solution here.

Categories
algorithms kotlin

Problem 5.8 from EPI -> Reverse digits of a number

Given a number like “123”, print out the reverse of that number like “321”!
There is a quick and easy way, convert the number to string and call string.reverse(), but it takes more memory than is neccessary.
A better way is to repeatedly take the most right number multiply it by 10 and add the next most right number, repeat until the number to reverse is zero.
Take a look at this code.
Happy coding!