Here is a simple solution that does not use strings or floating point functions / arithmetic. The usage of functions such as pow()
may run into problems as outlined in this question.
#include <iostream>
int main()
{
unsigned long long n = 1934L;
// save the original
unsigned long long final_number = n;
// multiplying factor
unsigned long long mult = 1;
// start by making sure we do not loop one too many times to
// calculate the multiplier
n /= 10;
while (n > 0)
{
// determines the multiplication factor after the loop
mult *= 10;
// strip off digit from number
n /= 10;
}
// create the final number from the original and the multiplication factor
final_number = (final_number % mult) * 10 + final_number / mult;
std::cout << final_number << "\n";
}
Live Example
Basically we count how many digits by looping, and at the same time increase the multiplying factor by 10. Then after the loop, the number is constructed by using modulus, multiplication, division, and addition.
So for example, after the loop, the final_number
would be
(1934 % 1000) * 10 + 1934 / 1000 =
934 * 10 + 1934 / 1000 =
9340 + 1934 / 1000 =
9340 + 1 =
9341
Note: I looked at the generated assembly language here and was amazed that the compiler is able to figure out the intent of the code, and computed 9341 at compile-time. I doubt the pow
solutions or floating point methods would produce these results.