Question

How to create all possible numbers, starting from a given one, where all digits of the new ones are moved one slot to the right? For example if we have 1234. I want to generate 4123, 3412 and 2341.

What I have come out with so far is this:

int move_digits(int a)
{
    int aux = 0;
    aux = a % 10;

    for(int i=pow(10, (number_digits(a) - 1)); i>0; i=i/10)
        aux = aux * 10 + ((a % i) / (i/10));
    return aux;
}

But it doesn't work.

The subprogram number_digits looks like this (it just counts how many digits the given number has):

int number_digits(int a)
{
    int ct = 0;
    while(a != 0)
    {
        a = a/10;
        ct++;
    }
    return ct;
}
Was it helpful?

Solution

I think there is no need to write separate function number_digits. I would write function move_digits simpler

#include <iostream>
#include <cmath>

int move_digits( int x )
{
    int y = x;
    double n = 0.0;

    while ( y /= 10 ) ++n;   
    return ( x / 10 + x % 10 * std::pow( 10.0, n ) );
}

int main()
{
    int x = 1234;

    std::cout << x << std::endl;
    std::cout << move_digits( x ) << std::endl;
}

OTHER TIPS

  • Retrieving the last digit of n: n % 10.
  • To "cut off" the last digit, you could use number / 10.
  • Say you have a three-digit number n, then you can prepend a new digit d using 1000 * d + n

That said, you probably want to compute

aux = pow(10, number_digits - 1) * (aux % 10) + (aux / 10)

Calculatea/(number_digits(a) - 1) and a%(number_digits(a) - 1)
And your answer is (a%(number_digits(a) - 1))*10 + a/(number_digits(a) - 1)

int i =0 ;
int len = number_digits(a);
while(i < len){
    cout << (a%(len - 1))*10 + a/(len - 1) <<endl;
    a = (a%(len - 1))*10 + a/(len - 1);
}
void move_digits(int a)
{
    int digits = 0;
    int b = a;
    while(b / 10 ){
        digits++;
        b = b / 10;
    }

    for (int i = 0; i < digits; ++i)
    {
        int c = a / 10;
        int d = a % 10;
        int res = c + pow(10, digits) * d;
        printf("%d\n", res);
        a = res;
    }
    printf("\n");
}
int main()
{
    move_digits(12345);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top