c++loopswhile-loopdo-while

I have some problems with assignment: Remove all digits that can be found on the left from most right digit 1


I started C++ in Uni. Now we are using loops. I have practical assignment: Task: Input: integer number. Remove all digits that can be found on the left from most right digit 1.

For example:

Or:

For this task we can not use arrays or strings. However we still can use math functions. Also there must obligatory be while/do while condition.

I have already written the code that finds values before the first digit 1 using % and /. However, as a result it doesn't work properly and when I enter something like 431004 - it will just show 4, not the 004. Here is my code:

#include <iostream>
using namespace std;
int main()
{
int number; 
cout << endl << "Enter integer number: ";
cin >> number;

int result;
int buffer = 0;
int divider = 10;
int check = 1;

do {
    result = buffer;
    buffer = number % divider;
    divider = divider * 10;
    check *= 10;
} while ((buffer / (check / 10)) != 1);

cout << endl << "Result = " << result; 

return 0;
}

Solution

  • 004 and 4 are ths ame number 4.

    If you need for example to output 4 as 004 then use manupulators std::setfill and std::setw declared in header <iomanip>.

    Also you should declare the variable number as having an unsigned integer type instead of the type int. Otherwise you need to take into account the sign of a number.

    Here is a demonstration program that shows how to get the expected result using the manipulators.

    #include <iostream>
    #include <iomanip>
    
    int main()
    {
        const unsigned int Base = 10;
    
        unsigned long long int number;
        
        std::cout << "Enter a non-negative integer number: ";
    
        if (std::cin >> number)
        {
            unsigned long long int result = 0;
            unsigned long long int multiplier = 1;
    
            int n = 0;
    
            while ( number && number % Base != 1 )
            {
                result += ( number % Base ) * multiplier;
                ++n;
                multiplier *= Base;
                number /= Base;
            }
    
            std::cout << "Result = " 
                << std::setw( n ) << std::setfill( '0' ) << result << std::endl;
        }
    }
    

    The program output might look like

    Enter a non-negative integer number: 431004
    Result = 004