Find the reverse of given number

For any given number we would need to return the number in reverse, with the starting place to the end place. For example, for an input of 1423 we would need to return 3241 which is its exact reverse. To achieve this, we would use the same principle we use for splitting the number; the Divisibility by 10 rule.

        public static int GetReversedNumber(int n)
        {
            int r, sum = 0, input = n;
            if (n < 10) return n;
            
            while (n != 0)
            {
                r = n % 10;
                sum = sum * 10 + r;
                n = n / 10;
            }
            return sum;
        }

How it works:

The logic starts in the same way as splitting the numbers, but for every time a remainder is obtained, it is added up on to a sum and before adding up the remainder the sum is multiplied with a 10 so that it grows in one place in the number.

For an input 1423:    

sum = 0*10 + 3 = 3   
sum = 3*10 + 2 = 32  
sum = 32*10 + 4 = 324  
sum = 324*10 + 1 = 3241
Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.