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).
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.
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
#include <iostream>
usingnamespace std;
int main()
{
longlong 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 );
}