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

前端 未结 19 1968
名媛妹妹
名媛妹妹 2020-12-14 03:29

I came across a question \"How can one reverse a number as an integer and not as a string?\" Could anyone please help me to find out the answer? Reversal should reverse the

19条回答
  •  执笔经年
    2020-12-14 03:55

    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

提交回复
热议问题