-3

How do I check how many numbers from 1 to N (N < 100) have number 3 in it without converting it to a string to check it?

user3711671
  • 823
  • 1
  • 6
  • 13
  • Possible duplicate: http://stackoverflow.com/questions/4977456/how-to-check-if-a-int-var-contains-a-specific-number – amito Sep 06 '15 at 09:51

3 Answers3

3

You can use th % mod operator to take the digits of the number one by one, and check them with 3.

Like,

int x;
while(num != 0)        // num here goes from 1 to 100
{
    x = num % 10;
    if(x == 3)
    {
        //eureka
    }
    num /= 10;
}

EDIT

Lets check the algorithm for 35.

First iteration

//num = 35

x = num % 10;           // x = 5 (35 % 10)
if(x == 3)             // is x equal to 3 (NO)
{
    //eureka
}
num /= 10;             // num = 3 (35 / 10)

While loop check

num != 0              // num = 5

Second Iteration

//num = 35

x = num % 10;           // x = 3 (5 % 10)
if(x == 3)             // is x equal to 3 (YES)
{
    //eureka
}
num /= 10;             // num = 0 (5 / 10)

While loop check

num != 0              // num = 0
                      // While loop exits
Haris
  • 12,120
  • 6
  • 43
  • 70
  • And when you get to 30? 30 % 10 = 0, 31 % 10 = 1, 32 % 10 = 2 – user3711671 Sep 06 '15 at 07:46
  • Its not `30 % 3`. Its `30 % 10`. – Haris Sep 06 '15 at 07:48
  • can you update the question with the new code. Make an **EDIT** section update – Haris Sep 06 '15 at 07:53
  • The code that you wrote, that you said is not working. – Haris Sep 06 '15 at 08:47
  • I didn't use your code because I don't even know that programming language (java maybe?) and because your algorithm is incorrect (or maybe I didn't understand your code because of the reason mentioned above).What your code does is that it checks the remainder of a number (from 1 to N ; N<100) divided by 10, right?If that's the case then it won't work because when you check for remainder of numbers from 30-39 you won't get 3 as a remainder (only 33 %10 = 3). – user3711671 Sep 06 '15 at 08:56
  • @user3711671 The algorithm is correct. If you can only understand code in some specific language, please indicate that in the tags. – Juan Lopes Sep 06 '15 at 12:46
2

I think the simplest way is by remainder and checking if number is between 30 and 39

if((x%10)==3||(x<40&&x>=30))
{
//Thats it
}
AguThadeus
  • 310
  • 2
  • 10
0

You can make use of the modulas operator % such that if(n % 3 == 1){success operation}

WeeniehuahuaXD
  • 852
  • 3
  • 10
  • 30