C#: Reverse the digits of a given signed 32-bit integer
C# Sharp Math: Exercise-10 with Solution
Write a C# Sharp program to reverse the digits of a 32-bit signed integer.
Sample Solution:
C# Sharp Code:
using System;
namespace exercises {
class Program {
static void Main(string[] args) {
int n;
n = 123456;
Console.WriteLine("Original Integer value: " + n);
Console.WriteLine("Reverse the digits of the said signed integer value:");
Console.WriteLine(reverse_integer(n));
n = -7654;
Console.WriteLine("Original Integer value: " + n);
Console.WriteLine("Reverse the digits of the said signed integer value:");
Console.WriteLine(reverse_integer(n));
n = 100;
Console.WriteLine("Original Integer value: " + n);
Console.WriteLine("Reverse the digits of the said signed integer value:");
Console.WriteLine(reverse_integer(n));
}
public static int reverse_integer(int x)
{
var result = 0;
var max_val = int.MaxValue / 10;
var min_val = int.MinValue / 10;
for (; x != 0; x /= 10)
{
if (result > max_val || result < min_val)
{
return 0;
}
result = result * 10 + x % 10;
}
return result;
}
}
}
Sample Output:
Original Integer value: 123456 Reverse the digits of the said signed integer value: 654321 Original Integer value: -7654 Reverse the digits of the said signed integer value: -4567 Original Integer value: 100 Reverse the digits of the said signed integer value: 1
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to calculate the full product of two 32-bit numbers.
Next: Write a C# Sharp program to convert a given string value to a 32-bit signed integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/csharp-exercises/math/csharp-math-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics