Jump to content

c++ backward integer

Go to solution Solved by Nineshadow,

@WildCAt It's pretty simple.

int rev(int n){    int x = 0;    while(n)    {        x = x * 10 + n%10;        n/=10;    }    return x;}

Do you understand how it works?

You initialize your new backward number to 0. Then, you make your new number itself times 10 (to make place for another digit) , then add the last digit of the original number. Then you divide your original number by 10 to get to the next digit and you keep going on until the original number becomes 0.

Hello! ^^

 

I am writing a program and I need to reverse my integer number to continue

For example, I have

 

int num_b; 

int num=123;

 

and I need   num_b   to be 321

 

I've been searching on the web, but found only int-string solutions or print numbers on screen step-by-step;

 

I do not need to print the number, I need to have my number to be int and reversed to continue calculations.

 

Can you help me?

And sorry for my English ^^"""

Link to comment
https://linustechtips.com/topic/470533-c-backward-integer/
Share on other sites

Link to post
Share on other sites

@WildCAt It's pretty simple.

int rev(int n){    int x = 0;    while(n)    {        x = x * 10 + n%10;        n/=10;    }    return x;}

Do you understand how it works?

You initialize your new backward number to 0. Then, you make your new number itself times 10 (to make place for another digit) , then add the last digit of the original number. Then you divide your original number by 10 to get to the next digit and you keep going on until the original number becomes 0.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
https://linustechtips.com/topic/470533-c-backward-integer/#findComment-6309078
Share on other sites

Link to post
Share on other sites

@WildCAt It's pretty simple.

int rev(int n){    int x = 0;    while(n)    {        x = x * 10 + n%10;        n/=10;    }    return x;}

Do you understand how it works?

You initialize your new backward number to 0. Then, you make your new number itself times 10 (to make place for another digit) , then add the last digit of the original number. Then you divide your original number by 10 to get to the next digit and you keep going on until the original number becomes 0.

 

Thanks!! ^_________^

Yeah, really simple)

Link to comment
https://linustechtips.com/topic/470533-c-backward-integer/#findComment-6309156
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×