Home > Software design >  How to swap a 2 digit number and find the larger of the result?
How to swap a 2 digit number and find the larger of the result?

Time:10-19

I want to use the number 25 then swap the two digits (the 2 and the 5) and then compare the swapped number (52) to the first number (25). If the swapped number is bigger I get a true and if the swapped number is smaller than the first number I get a false.

Example of what I want:

Input:

25

Output:

True //Because 25 reversed is 52, so it´s bigger 

This is what I've tried:

        int firstdigit = num / 10;
        int secondigit = num % 10;
        string res = secondigit   firstdigit.ToString();
        
        if(res > num)
        {
            return true;
        }
        return false;

The problem now is that the "if" is not working anymore because res is a string and num is an int, but when I make res an int then I cant add the first digit and second digit because it's obviously different if I do 5 2 with ints (7) or 5 2 with strings (52).

CodePudding user response:

You need to construct the reversed int value and compare against that:

int firstdigit = num / 10;
int secondigit = num % 10;
int reversed   = firstdigit   seconddigit * 10;

if (reversed > num)
    ...

If you look at the code above, you should see that it's just reversing the logic that you used to extract the first and second digits.

CodePudding user response:

Constructing int from the beginning works (as answered by others already), and probably is more efficient, but since you asked this question - you might be interested in this guide.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number

So you can convert your constructed string back to number to be able to compare it.

  • Related