Home Why isn't my loop method working?
Reply: 0

Why isn't my loop method working?

user1213
1#
user1213 Published in May 25, 2018, 11:09 am

This may be a simple problem for many, but I cannot for the life of me figure out what is wrong with my code.

I am supposed to return the number of numbers under n (max 1000000) that have both a 7 and a 9 in them. For example, n=10 returns 0, n=100 returns 2 (from 79 and 97) etc.

int allWith7Or9(int n) 
{
  int count = 0;
  for(int i = 0; i < n; i++)
  {
    if(i%10==7 || i%100==7 || i%1000==7 || i%10000==7 || i%100000==7 || i%1000000==7)
    {
      if(i%10==9 || i%100==9 || i%1000==9 || i%10000==9 || i%100000==9 || i%1000000==9)
      {
        count++;
      }
    }
  }
  return count;
}

I realize that I could have used &&, and I tried to, but my code keeps coming up with 0, and I have no idea why. I implemented this at least 3 different ways.

EDIT:

I also tried this:

int allWith7Or9(int n) 
{
  int count = 0;
  for(int i = 0; i < n; i++)
  {
    if((i%10==7 || i%100==7 || i%1000==7 || i%10000==7 || i%100000==7
    || i%1000000==7) && (i%10==9 || i%100==9 || i%1000==9
    || i%10000==9 || i%100000==9 || i%1000000==9))
    {
      count++;
    }
  }
  return count;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.349286 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO