 Reverse integer number with while loop | Sololearn: Learn to code for FREE!

+30

# Reverse integer number with while loop

+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

+18

no just reverse every single character of number like input : 768 output : 867

+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());

+11

Its very simple 1. Convert integre to character array 2. Use inverse character array like this code #include <stdio.h> // printf #include <stdlib.h> // malloc, free #include <string.h> // 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 = {'-', '1', '2', '3', '\0'}; int i; sscanf(myarray, "%d", &i);

+8

Jay Matthews I was more addressing the answer given by Ariela

+3

https://code.sololearn.com/chhVtwlgKVLD/?ref=app

+2

What do you mean? Like reverse an array of ints?

+2

One sec I’ll write the code for you

+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]; }

+2

This would be much easier done with a for loop or just using methods

+2

And at the end just convert reverse to an int

+2