+ 2
How would you reverse a number
// From int target = 12345; // To int result = 54321; Any answer is appreciated 👍
14 Réponses
+ 5
Delicate Cat
Normally I would do this but it looks amateur and I'm pretty sure the performance is awful, which is why I didn't care to show my attempt 😉
https://code.sololearn.com/cR8e68JxvGqS/?ref=app
+ 4
https://www.c-sharpcorner.com/blogs/reverse-a-number-and-string-in-c-sharp1
+ 3
int target = 12345;
char[] temp = target.ToString().ToCharArray();
Array.Reverse(temp);
int result = Int32.Parse(String.Join("",temp));
Console.WriteLine(result);
+ 3
Ugh, nvm, I don't know how to reverse it the other way around
+ 3
Andy_Roid
Thank you, Andy
+ 2
you can do it like this,
https://code.sololearn.com/cT2K5Rz3QXc3/?ref=app
+ 2
your method would have worked, but u need to start from the last element to first element, you can do that by using for loop.
https://code.sololearn.com/cOKUlp6xN5E6/?ref=app
+ 2
https://code.sololearn.com/cPq5qjskrdKH/?ref=app
hope this helps u
+ 2
//In C language
#include<stdio.h>
void main() {
int target = 12345, result = 0, r;
while(target > 0) {
r = target % 10;
result = (result * 10) + r;
target /= 10;
}
printf("%d", result);
}
Hope its easier for you convert into c#
+ 2
Kartik Singh Negi
Very detailed and comprehensible, thanks for putting much effort into this 😉
+ 1
Rushikesh
Thank you 😀
+ 1
int target =12345;
int rem=0, rev=0 ,result=0;
while(target!=0)
{
rem=target%10;
rev=rev*10+rem;
target=target/10;
}
result=rev;
To reverse a number we need to get last number at first second last at second .......
In loop
//rem =5
//rev=0+5=5
//target =1234
Again
// rem=4
//rev=5*10+4=54
//target=123
Again
//rem=3
//rev=54*10+3=543
//target=12
Again
//rem=2
//rev=543*10+2=5432
//target=1
Again
//rem=1
//rev=5432*10+1=54321
//target=0
And ends because target becomes 0
+ 1
Abirami
Thanks for the code 👍
+ 1
We can reverse a number in C# using loop and arithmetic operators. In this program, we are getting number as input from the user and reversing that number.
Let's see a simple C# example to reverse a given number.
using System;
public class ReverseExample
{
public static void Main(string[] args)
{
int n, reverse=0, rem;
Console.Write("Enter a number: ");
n= int.Parse(Console.ReadLine());
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
Console.Write("Reversed Number: "+reverse);
}
}