Reverse integer number with while loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 30

Reverse integer number with while loop

27th Mar 2018, 10:31 PM
AliR૯za
AliR૯za - avatar
9 Answers
+ 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
+ 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[5] = {'-', '1', '2', '3', '\0'}; int i; sscanf(myarray, "%d", &i);
27th Mar 2018, 11:22 PM
hossein B
hossein B - avatar
18th Apr 2018, 5:57 AM
Masoud Rabiee
Masoud Rabiee - 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