Cristii
Cristii

Reputation: 13

C# Reverse the first 2 digits of an unknown digit number?

So i'm making a game, where you have to calculate the next number in the fibonnaci seq. on a timer

Ex.  0, 1 => next number = 1
     1, 2 => next number = 3
     2, 3 => next number = 5

And so on...

The thing is... once you get to bigger numbers, that are harder to calculate, you would want to do basic addition, from right to left. So you have 2 options, either do it in your mind, or type it down and reverse the number after, which is exactly what I have coded it to do.

It is reversing the number, using the normal algorithm for it, but there is one problem.

Normally, you go from right to left with the math, and type every digit down, and once you get to adding the last digits of the 2 numbers, if the sum of these 2 goes over 10, you just write the number before the other digits

Ex: 

567 + 723

1. 7 + 3 => 0                      Number = 0
2. 6 + 2 = 8 + the carried 1 = 9   Number = 90
3. 5 + 7 = 12                      Number = 1290

In the input bar, you would type it like 0912, but that wouldn't work since the 12 has to be reversed as well into 21. Since I don't want this to be a nuisance for the player, the question is

How do I reverse the first digits 2 digits of a number?

My guess would be adding 1 variable that stores the reversed sum of the numbers, and then 2 other variables storing the number after the first 2 digits in one, and the other one storing the first 2 digits and reversing them, then adding the first 2 digits reversed to the other part multiplied by 100

Even so, I don't believe it is my best options, since I can't be sure if the numbers are 3 digits with sum >999 or normal 4 digits with the sum <9999

If you have any better ideas, please tell me. If you have any questions about my code, I'll gladly post it My apologies if this is hard to understand, the human mind is hard to explain.

Upvotes: 1

Views: 869

Answers (1)

Blindy
Blindy

Reputation: 67584

A relatively simple way is this (see it live here):

public static long SwapFirstTwoDigits(long val)
{
    if(val < 10) return val;
    
    long mask;
    for(mask = 1; mask < val; mask *= 10) {}
    mask /= 100; // two back
    
    var firstTwoDigits = val / mask;
    return val % mask + (firstTwoDigits % 10) * mask * 10 + firstTwoDigits / 10 * mask;
}

Basically you build the base 10 mask of all the digits you want to leave alone (so two behind the first two digits from the right) and simply swap the rest with modulo arithmetic.

Output from the linked fiddle:

Input: 1530, Output: 5130
Input: 16789, Output: 61789
Input: 34, Output: 43
Input: 3, Output: 3
Input: 0, Output: 0

Upvotes: 1

Related Questions