• 0

reversing integer numbers?


Question

I just came back from a MS interview and I was asked to reverse integer numbers. Needless to say I completely bombed the question. You can't use toString () methods and use the reverse string function call ( I tried to do that). So how do you reverse integer numbers mathematically?! Say I have an integer 123, how do I mathematically manipulate it so it comes out to be 321?

Link to comment
https://www.neowin.net/forum/topic/287002-reversing-integer-numbers/
Share on other sites

9 answers to this question

Recommended Posts

  • 0

Think of the (decimal) number 123 as 1 * 10 ^ 2 + 2 * 10 ^ 1 + 3 * 10 ^ 0, now this should map to 3 * 10 ^ 2 + 2 * 10 ^ 1 + 3 * 10 ^ 0.

In Haskell

reverseInt :: Int -> Int
reverseInt i  = let calculateInt n b
    | null n = 0
  	| otherwise = (head n) * 10  ^ (b) + calculateInt (tail n) (b+1) 
	in
	calculateInt (sepInt i) 0 where
  sepInt i
   | i == 0  = []
   | otherwise = (sepInt (i `div` 10)) ++ [(i `mod` 10)]

  • 0
  Elagizy said:
Hey... Check this >>

Imports vb = Microsoft.VisualBasic

Text1.Text = vb.StrReverse("123") -------- > 321

585500504[/snapback]

  Quote
You can't use toString () methods and use the reverse string function call ( I tried to do that). So how do you reverse integer numbers mathematically?!

I never even thought of the string reverse method. That would've been slick.

Here's what I came up with.

private int Reverse(int value)
  {
  	int reverse = 0;
  	while(value > 0)
  	{
    int part = value % 10;
    value /= 10;
    reverse *= 10;
    reverse += part;
  	}
  	return reverse;
  }

  • 0

for those of you who want this in vb, here it is

Private Shared Function Reverse(ByVal num As Integer) As Integer
	Dim value As Integer

	While num > 0
  Dim part As Integer = num Mod 10
  num \= 10   'must use integer division instead of normal division
  value *= 10
  value += part
	End While

	Return value
End Function

the only weird part is the use of backwards slash, which denotes integer division in vbnet

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.