Swap second digit with penultimate

How can i invert the second digit of a number with the penultimate using the mathematical order and powers of 10?
Simple solution with while and if (if it's possible).

Restriction: 9 < N < 1.000.000.000

Input : 123456 Output: 153426
It would seem to be easier to just mess around with the original input string.
do it as text is correct.
if you MUST do this as int,
log10 can be used to get the # of digits, from there you just divide by 10 to the number of digits -2 (this gives 12 in 123456) and then %10 gives you 2. subtract the result (2) * 10 to the number of digits -2 and you get 103456. A similar process can extract the 5 (you don't need log10 here, you KNOW what to use. the log 10 is because you don't know if its 1234 or 12345 or 12345678 etc.. but they all have a 10's digit). Add back the digits * the appropriate power of 2, that is you end up with 103406 and add 50000 and 20

you do not need while nor if. its straight up step by step. (note: (int) log10(x) is number of digits -1).

This is the brute force answer. There may be a clever way to do it.
Last edited on
#include <iostream>
#include <math.h>

using namespace std;

int main(){
long N, cN, cifre=0,Ni,x,y,ultima,prima,mij;
cin>>N;
cN=N;
while (cN!=0){
cN=cN/10;
cifre++;
}
ultima=N%10;
prima=N/pow(10,cifre-1);
mij=N%pow(10,cifre-2)/100;
x=N%pow(10,cifre-1)/pow(10,cifre-2);
y=N%100/10;
Ni=prima*pow(10,cifre-1)+y*pow(10,cifre-2)+mij*100+x*10+ultima;
N=Ni;
cout<<Ni;
return 0;
}

||=== Build: Debug in Swaps (compiler: GNU GCC Compiler) ===|
D:\Projects C++\Swaps\main.cpp||In function 'int main()':|
D:\Projects C++\Swaps\main.cpp|16|error: invalid operands of types 'long int' and 'double' to binary 'operator%'|
D:\Projects C++\Swaps\main.cpp|17|error: invalid operands of types 'long int' and 'double' to binary 'operator%'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|


if I declare them int it gives me other errors that int is not enough
Last edited on
Cast the pow calls to long, you can't do % on a double.

Edit: s/int/long/
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
   long long n, nn, p = 1;
   cout << "Enter n: ";   cin >> n;
   nn = n;
   while ( nn > 100 )
   {
      nn /= 10;
      p *= 10;
   }
   int second = nn % 10, penultimate = n % 100 / 10;
   cout << n + ( p - 10 ) * ( penultimate - second );
}
Enter n: 123456
153426
Topic archived. No new replies allowed.