Numbers containing digit 1,2 and 3

Can someone give me a hint on how to write the code to find out whether number 0000 to 9999 entered contain digit 1, 2 or 3? I know doing % 3 is wrong

cout << "Enter the desired number :";
cin >> number;

if (number < 0 || number > 9999)
cout << "Invalid entry, pls re-enter number between 0 and 9999" << endl;

else
{
answer = number % 3;
if (answer >= 1 && answer <= 3)
cout << "Entered number, " << number << " contains the digit 1, digit 2 or digit 3" << endl;
else
cout << "Entered number, " << number << " does not contain the digit 1, digit 2 or digit 3" << endl;
}
Why not convert the number to a string and then just search for the characters you're interested in?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
    int number = 3875 ; // for example (non-negative)

    std::cout << "the number " << number << " contains the digits " ;

    while( number != 0 ) // repeat till we have nothing left
    {
        const int last_digit = number % 10 ; // 3875%10 yields 5
        std::cout << last_digit << ' ' ; // print out the digit

        number /= 10 ; // dividing by 10 throws away the last digit
                       // 3875/10 == 387; last digit of 387 is 387%10 == 7
                       // 387/10 == 38; last digit of 38 is 38%10 == 8 etc.
    }

    std::cout << " (in reverse order)\n" ;
}
This is the simplest way to do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

int main()
{
	int num;
	do
	{
		std::cout << "Enter number (0 to 9999): ";
		std::cin >> num;
	} while (num < 0 || num > 9999);
	
	int o, t, h, th;
	
	//to get all the digits separately
	o = num / 1 % 10;          //ones
	t = num / 10 % 10;	   //tens
	h = num / 100 % 10;    //hundreds
	th = num / 1000 % 10;  //thousands
	
	if (o == 1 || o == 2 || o == 3 || t == 1 || t == 2 || t == 3 ||
		h == 1 || h == 2 || h == 3 || th == 1 || th == 2 || th == 3)
	{
		std::cout << "Entered number, " << num << ", contains the digit 1, 2 or 3." << std::endl;
	}
	else
	{
		std::cout << "Entered number, " << num << ", does not contain the digit 1, 2 or 3." << std::endl;
	}
	return 0;
}
Last edited on
And now for some fun mathematical reading:
http://www.cut-the-knot.org/do_you_know/digit3.shtml
Topic archived. No new replies allowed.