+ 30

Reverse integer number with while loop

27th Mar 2018, 10:31 PM
AliR૯za
AliR૯za - avatar
12 Answers
+ 12
I think it's like reversing a number like 123 ➡ 321. Here's a general algorithm for it: (1) Initialize a variable to keep track of the reversed number (rev) to 0 (2) Loop while num > 0 (a) Multiply rev by 10 (b) add remainder of num to rev **a shorter way to think about all the above steps: rev = rev*10 + num%10; (d) Divide num by 10 The result at the end of the loop is the number reversed. Example: 369 rev = 0 369 > 0, loop rev = 0*10 + 369%10 = 9 num = 369/10 = 36 36 > 0, loop rev = 9*10 + 36%10 = 96 num = 36/10 = 3 3 > 0, loop rev = 96*10 + 3%10 = 963 num = 3/10 = 0 0 > 0 is false, stop loop rev = 963, the reverse of 369
27th Mar 2018, 10:57 PM
Ace
Ace - avatar
+ 18
no just reverse every single character of number like input : 768 output : 867
27th Mar 2018, 10:49 PM
AliR૯za
AliR૯za - avatar
+ 13
There's a much shorter way if using strings instead of numbers. C++ has a reverse method in the header <algorithm>. Given a string of numbers (num), just pass it to reverse like so: reverse(num.begin(), num.end());
27th Mar 2018, 11:11 PM
Ace
Ace - avatar
+ 11
Its very simple 1. Convert integre to character array 2. Use inverse character array like this code #include <stdio.h> // printf #include // malloc, free #include // strlen int main() { char* s = "hello"; size_t l = strlen(s); char* r = (char*)malloc((l + 1) * sizeof(char)); r[l] = '\0'; int i; for(i = 0; i < l; i++) { r[i] = s[l - 1 - i]; } printf("normal: %s\n", s); printf("reverse: %s\n", r); free(r); } Finally return it to integer like this code char myarray[5] = {'-', '1', '2', '3', '\0'}; int i; sscanf(myarray, "%d", &i);
27th Mar 2018, 11:22 PM
hossein B
hossein B - avatar
+ 8
Jay Matthews I was more addressing the answer given by [user id="8591406"]Ariela[/user]
27th Mar 2018, 11:21 PM
Ace
Ace - avatar
18th Apr 2018, 5:57 AM
ThieF_[Css]
ThieF_[Css] - avatar
+ 2
What do you mean? Like reverse an array of ints?
27th Mar 2018, 10:40 PM
Ariela
Ariela - avatar
+ 2
One sec I’ll write the code for you
27th Mar 2018, 10:57 PM
Ariela
Ariela - avatar
+ 2
int num = 768; std::string s = std::to_string(num); std::string reverse = “”; char cstr[] = s.c_str(); int i = 0; while (s.length() != reverse.length()){ i++; reverse += cstr[cstr.length()-i]; }
27th Mar 2018, 11:01 PM
Ariela
Ariela - avatar
+ 2
This would be much easier done with a for loop or just using methods
27th Mar 2018, 11:02 PM
Ariela
Ariela - avatar
+ 2
And at the end just convert reverse to an int
27th Mar 2018, 11:02 PM
Ariela
Ariela - avatar
+ 2
decreasing integer loop
3rd Apr 2018, 6:14 AM
Uthuma Lebbe Mohamed Ahnaf Shihab
Uthuma Lebbe Mohamed Ahnaf Shihab - avatar