Inverse number with leading zeros

How do we convert a number with leading zeros to a number? For example: if the input is 004, the output should be 400.

I wrote the program below, but it only works when there are no leading zeros in the input.

int num;
cout<<"Enter number "<<endl;
cin>>num;

int rev = 0;
int reminder;
while(num != 0)
{
    reminder = num % 10;
    rev = rev * 10 + reminder;
    num = num / 10;
}
cout<<"Reverse = "<<rev<<endl;

Is there a way to enter a number with leading zeros? Even then, the above logic does not work for such numbers.

Any simple solution? This is doable by accepting the input as a string and processing it. But it does not look beautiful.

* EDIT: if the length of the number is known, it can be turned to a number with zero values. (without using a string) *

I will send the code as soon as it works.

EDIT 2: I tried to return the characters to the cin stream and then read and calculate the opposite. It works for two-digit numbers.

, . , , 10 . , . , :)

+3
10

(int, double ..). , , std::string. , std::reverse(), .

+6

, . int.

+6

, , , , , ( ) . . , , .

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;

.

+2

( std::string) .

+1

, 3, .

.

+1

, ...

#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';
}
+1

ChrisF, , 4 004 - int, int.

, , , ( ) std::reverse - .

0

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

while for , , ( ). 004 , 3 x == 0.

0
s = int(raw_input(" enter the no of tyms :"))
n = 0
list, list1 = [], []

while n <= s:
    m = raw_input("enter the number:")
        n=n+1
        list.append(m)

print list
list.reverse()
print list

Python.

0
source

Source: https://habr.com/ru/post/1774562/


All Articles