Reverse the number problem

Why this is saying time limit exceeded any help

#include
using namespace std;

int reversenumber(int num)
{
while(num > 0)
{
num = num * 10 + num % 10;
num /= 10;
}
return num;
}

int main() {
// your code goes here
int n, num;
cin >> n;
while(nā€“)
{
cin >> num;
reversenumber(num);
}

return 0;

}

Suppose num = 1.
Your code runs like this :
1 -> 11 -> 1 -> 11 -> 1 -> 11 ā€¦

Do this to reverse the number :

int reversenumber(int num)
{
    int res = 0;
    while(num!=0)
        res = res * 10 + num%10 , num/=10;
    return res;
}

OR YOU CAN DIRECTLY DO THIS

#include<bits/stdc++.h>
using namespace std;
int main()
{
  int t;
  cin >> t;
  while(t--)
  {
    string s;
    cin >> s;
    reverse(s.begin(),s.end());
    cout << s << endl;
  }
}

you should store reverse of number in diffrent variable how you are doing into same num its not going to work
Refer this:

rev = 0
while(num!=0){
    rev = num%10 + rev*10;
    num/=10
}
return rev

If you have any questions?

1 Like