Selenium C sharp Question1 – How to reverse a number

Following method is useful to reverse a number in C#. Call it in a class under Main method for execution.

int ReverseNumber(int number)
{
int reversed = 0;

int digit = 0;
while (number != 0)
{
digit = number % 10;
reversed = reversed * 10 + digit;
number = number/10;
}
return reversed;
}

Explanation: When a number is passed to the ReverseNumber method, we initialize two variables: reversed (to store the reversed number) and digit (to hold the last digit during each iteration), both set to zero initially.

We then use a loop that continues as long as the number is not zero. Inside the loop:

  1. We extract the last digit of the number by using the modulus operator (number % 10) and assign it to the digit variable.
  2. We update the reversed variable by multiplying its current value by 10 and adding the extracted digit. This effectively shifts the digits of reversed to the left and appends the new digit at the end.
  3. We remove the last digit from the original number by dividing it by 10 (number / 10) and assigning the result back to number. This discards the digit we just processed.

This process repeats until the number becomes zero. At that point, the loop exits and the method returns the reversed variable, which now holds the digits of the original number in reverse order.

Sample number: 123 Result: 321

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x