1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
int swapDigits( int m, int n, int x )
{
/*
m = 2, n = 3, x = 12345
expected result = 13245
13245 - 12345 = 900
m = 1, n = 3, x = 14793
expected result = 74193
74193 - 14793 = 59400
m = 2, n = 5, x = 26937
expected result = 27936
27936 - 26937 = 999
in all these, there is a pattern.
in example 1,
noOfDigits = 5
a = noOfDigits - m b = noOfDigits - n c = nth digit - mth digit
x = 3 = 2 = 3 - 2
= 1
(10^a - 10^b) * c = (1000 - 100) * 1
= 900
in example 2,
a = 4 b = 2 c = 6
(10^4 - 10^2) * 6 = 59400
in example 3,
a = 3 b = 0 c = 1
(10^3 - 10^0) * 1 = 999
see the pattern?
*/
/*
add checks:
m < n < noOfDigits
check the validity of c, i.e. what if the nth digit is greater than the mth digit?
whatever else you can think of
*/
int temp{ x }, noOfDigits{ 0 };
while( temp % 10 ) {
noOfDigits++;
temp /= 10;
}
int mthDigit{ 0 }, nthDigit{ 0 };
/*
find a way to do this
mthDigit =
nthDigit =
*/
int a{ noOfDigits - m }, b{ noOfDigits - n }, c{ /*fix me*/ };
int d = (pow(10, a) - pow(10, b)) * c;
return x + d;
}
|