Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Discuss: 1.If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.
2.Reversed integer overflow.
public static int ReverseInteger(int num) { bool is_neg = num < 0; int newNum = Math.Abs(num); int result = 0; while (newNum > 0) { result = result * 10 + (newNum % 10); newNum /= 10; } if (is_neg) result *= -1; return result; }
时间: 2024-10-04 22:58:22