开发者

How to reverse a number as an integer and not as a string?

I came across a question "How can one reverse a number as an integer and not as a strin开发者_StackOverflow中文版g?" Could anyone please help me to find out the answer? Reversal should reverse the decimal digits of the number, i.e. use base 10.


Something like this?

public int ReverseInt(int num)
{
    int result=0;
    while (num>0) 
    {
       result = result*10 + num%10;
       num /= 10;
    }
    return result;
}

As a hackish one-liner (update: used Benjamin's comment to shorten it):

num.ToString().Reverse().Aggregate(0, (b, x) => 10 * b + x - '0');

A speedier one-and-a-quarter-liner:

public static int ReverseOneLiner(int num)
{
    for (int result=0;; result = result * 10 + num % 10, num /= 10) if(num==0) return result;
    return 42;
}

It's not a one-liner because I had to include return 42;. The C# compiler wouldn't let me compile because it thought that no code path returned a value.

P.S. If you write code like this and a co-worker catches it, you deserve everything he/she does to you. Be warned!

EDIT: I wondered about how much slower the LINQ one-liner is, so I used the following benchmark code:

public static void Bench(Func<int,int> myFunc, int repeat)
{
    var R = new System.Random();
    var sw = System.Diagnostics.Stopwatch.StartNew();
    for (int i = 0; i < repeat; i++)
    {
        var ignore = myFunc(R.Next());
    }
    sw.Stop();
    Console.WriteLine("Operation took {0}ms", sw.ElapsedMilliseconds);
}

Result (10^6 random numbers in positive int32 range):

While loop version:
Operation took 279ms

Linq aggregate:
Operation took 984ms


This should do it:

int n = 12345;
int left = n;
int rev = 0;
while(Convert.ToBoolean(left)) // instead of left>0 , to reverse signed numbers as well
{
   int r = left % 10;   
   rev = rev * 10 + r;
   left = left / 10;  //left = Math.floor(left / 10); 
}

Console.WriteLine(rev);


using System; 

public class DoWhileDemo {   
  public static void Main() { 
    int num; 
    int nextdigit; 

    num = 198; 

    Console.WriteLine("Number: " + num); 

    Console.Write("Number in reverse order: "); 

    do { 
      nextdigit = num % 10; 
      Console.Write(nextdigit); 
      num = num / 10; 
    } while(num > 0); 

    Console.WriteLine(); 
  }   
}


multiply it by -1? precise your question please...


Yay! A bling way. (No, really. I hope that this is more a "How would I do..." question and not something you really need in production)

public int Reverse(int number) {
  return int.Parse(number.ToString().Reverse().Aggregate("", (s,c) => s+c));
}


Check below simple and easy -

public int reverseNumber(int Number)
{
  int ReverseNumber = 0;
  while(Number > 0)
  {
    ReverseNumber = (ReverseNumber * 10) + (Number % 10);
    Number = Number / 10;
  }
  return ReverseNumber;
}

Reference : Reverse number program in c#


Old thread, but I did not see this variation:

        int rev(int n) {
            string str = new String(n.ToString().Reverse().ToArray());
            return int.Parse(str);
        }


You can't. Since the computer thinks in hexadecimal in any case, it is necessary for you to tokenise the number into Arabic format, which is semantically identical to the conversion to string.


    /// <summary>
    /// Reverse a int using its sting representation.
    /// </summary>
    private int ReverseNumber(int value)
    {
        string textValue = value.ToString().TrimStart('-');

        char[] valueChars = textValue.ToCharArray();
        Array.Reverse(valueChars);
        string reversedValue = new string(valueChars);
        int reversedInt = int.Parse(reversedValue);

        if (value < 0)
           reversedInt *= -1;

        return reversedInt;
    }


I looked at the following solution. But how about when n is negative?

Lets say n = -123456

Here is a tweak I added to it to handle negative numbers, with that assumption it will threat negative numbs the same way.

        int reverse = 0;
        bool isNegative = false;

        if (n < 0)
            isNegative = true;

        n = Math.Abs(n);
        while (n > 0)
        {
            int rem = n % 10;
            reverse = (reverse * 10) + rem;
            n = n / 10;
        }

        if (isNegative)
            reverse = reverse * (-1);

        return reverse;


the shortest solution:

        int reverse=0;
        int number = 21;

        while (number > 0)
        {
            reverse = number % 10;
            Console.Write(reverse);
            number = number / 10;  
        }


As per Pritam Karmakar comment , Yes this will not work when given number has 0 at end. If you pass number as 150 it will return 51 not 051. so i had write code to display number in Reverse order as per user input please check this.

int reverseNum = 0, reminder, num;
        Console.WriteLine("Enter Number to Reverse:");
        int.TryParse(Console.ReadLine(), out num);
        bool isZero = false;
        int cnt=0;
        while (num > 0)
        {
            reminder = num % 10;
            reverseNum = (reverseNum * 10) + reminder;
            num = num / 10;
            if (reverseNum == 0)
                isZero = true;                
            cnt++;
        }
        if (isZero)
        {
            Console.WriteLine(reverseNum.ToString().PadLeft(cnt, '0'));
        }
        else
        {
            Console.WriteLine(reverseNum);
        }
        Console.ReadKey();


    public static void Main(string[] args)
    {
        int reversed = Reverse(-7360);
    }

    public static int Reverse(int number, int left = 0, int right = 0)
    {
        if (number == 0) return left + right;
        return Reverse(number / 10, left * 10 + right * 10, number % 10);
    }


    static void Main(string[] args)
    {
        Console.WriteLine("Please enter number");
        int number = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(ReverseLoop(number));
        Console.WriteLine(ReverseRecursive(number));
        Console.ReadLine();
    }

    public static int ReverseRecursive(int number)
    {
        int remainder = number % 10;
        number = number / 10;
        if (number < 1)
            return remainder;
        return ReverseRecursive(number) + remainder * Convert.ToInt32(Math.Pow(10, number.ToString().Length));
    }

    public static int ReverseLoop(int number)
    {
        int reversed = 0;
        while (number > 0)
        {
            reversed = reversed * 10 + (number % 10);
            number = number / 10;
        }
        return reversed;
    }


Solution suggested by @jerjer and @cfern is perfect but It will not work for negative int number like -1234507.

Solution : If number is negative int then multiply by -1 after that call your method ReverseInt(-1234507)

    int number = -1234507;
    **number = number > 0 ? number : (number * -1);**

    int reverseNumber = 0;

    while(number > 0){
        reverseNumber = (reverseNumber * 10) +  (number % 10) ;
        number = number / 10;
    }
    Console.WriteLine(reverseNumber);


You can do something like this.

Convert.ToInt32(new string(num.ToString().Reverse().ToArray()));


int x = 9876543;
char[] arr = x.ToString().ToCharArray();
Array.Reverse(arr);
Console.WriteLine(int.Parse(new string(arr)));


int sum = 0; int remainder = 0;
        int n = 123;
        for (int i = n; i > 0; i = i / 10)
        {
            remainder = i % 10;
            sum = (sum * 10) + remainder;
        }
Console.WriteLine(sum);
Console.ReadLine();


a new one:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        int i = 234;
        int j = -123;
        Console.WriteLine(reverse(i));
        Console.WriteLine(reverse(j));
    }

    static int reverse(int i)
    {
        int sign = i / Math.Abs(i);
        var abs = string.Concat(Math.Abs(i).ToString().Reverse());
        return int.Parse(abs) * sign;
    }
}

https://dotnetfiddle.net/VGJJFf

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜