简体   繁体   中英

code for reversing an integer in cpp using operators

the code is for reversing the input decimal whether negative or positive.if the value of decimal exceeds as max size of int in 32 bit system then return 0.why my code is not working...help me finding the bug.i have attached the code.

#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
float reverseint(int x)
{
    int digit[10];
    int i = 0;
    float revnum = 0;
//store digits of number x
    while (x != 0)
    {
        digit[i] = x % 10;
        x = x / 10;
        i++;
    }
    i--;
//reversing number x
    while (i >= 0)
    {
        int j = 0;
        revnum = (digit[i] * pow(10, j)) + revnum;
        j++;
        i--;
    }
    return revnum;
}
int main()
{
    int n;
    cin >> n;
    if (n < 0)
    {
        if (n < -pow(2, 31))
            cout << 0 << endl;
        cout << -reverseint(-n);
    }
    if (n > 0)
    {
        if (n > (pow(2, 31) - 1))
            cout << 0 << endl;
        cout << (reverseint(n)) << endl;
    }
    return 0;
}

You are initializing j variable on every while loop on reverseint function.

float reverseint(int x)
{
    int digit[10];
    int i = 0;
    float revnum = 0;
//store digits of number x
    while (x != 0)
    {
        digit[i] = x % 10;
        x = x / 10;
        i++;
    }
    i--;
//reversing number x
    int j = 0; /// Correct place.
    while (i >= 0)
    {
        //int j = 0; /// Wrong. j will be always 0 on every loop. revnum  will be sum of digits on variable x.
        revnum = (digit[i] * pow(10, j)) + revnum;
        j++;
        i--;
    }
    return revnum;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM