Search code examples
c#swap

How to swap a 2 digit number and find the larger of the result?


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).


Solution

  • 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.