Reverse of a number with leading zeroes

后端 未结 10 1541
庸人自扰
庸人自扰 2021-01-14 05:17

How do we reverse a number with leading zeroes in number ? For ex: If input is 004, output should be 400.

I wrote below program but it works only when n

相关标签:
10条回答
  • 2021-01-14 05:52

    Once you convert your input to an integer, which you do in line 3, any information about the leading zeroes in the input of the user is lost.

    You'll have to use a string.

    0 讨论(0)
  • 2021-01-14 05:54

    Read the number in string format (that is, use std::string) and reverse the string.

    0 讨论(0)
  • 2021-01-14 05:56

    A recursive approach, but easily converted to a loop...

    #include <iostream>
    
    int f(int value = 1)
    {
        char c;
        return (std::cin.get(c) && isdigit(c))
               ? (c - '0') * value + f(10 * value)
               : 0;
    }
    
    
    int main()
    {
        std::cout << f() << '\n';
    }
    
    0 讨论(0)
  • 2021-01-14 05:57

    If you know the total width you'd like the number to be before-hand, you can reuse the code you have and store the results (from right to left) in a zero initialized array. Note: you'd probably want to add some error checking to the code listed below.

    int num, width;
    
    cout<<"Enter number "<<endl;
    cin>>num;
    
    cout<<"Enter width: "<<endl;
    cin>>width;
    
    int rev[width];
    for (int i = 0; i < width; ++i)
        rev[i] = 0;
    
    int cnt = width - 1;
    int rev = 0;
    int reminder;
    while(num != 0)
    {
        reminder = num % 10;
    //    rev = rev * 10 + reminder;
        rev[cnt] = remainder;
        --cnt;
        num = num / 10;
    }
    
    cout << "Reverse: ";
    for (int i = 0; i < width; ++i)
        cout << rev[i];
    cout << endl;
    

    This will allow you to manipulate the number more easily in the future as well.

    0 讨论(0)
  • 2021-01-14 06:00

    Keep the number as a string, and use std::reverse.

    std::string num;
    std::cout << "Enter number " << std::endl;
    std::cin >> num;
    
    std::string rev(num);
    std::reverse(rev.begin(), rev.end());
    
    std::cout << "Reverse = " << rev << std::endl;
    
    0 讨论(0)
  • 2021-01-14 06:01

    Yes, you must use a string. You cannot store leading zeros in an int.

    0 讨论(0)
提交回复
热议问题