Thread: Checking whether an integer value has a certain integer in it.

1. Member Join Date
Oct 2013
Posts
13
Rep Power
0 Checking whether an integer value has a certain integer in it.

Say we have an array of integers 1 through 10000.
We also have 3 instance variables; sum, sumWith8s, sumWithout8s.

Sum is the sum of all the values 1 through 10000,
sumWith8s is the sum of all the values 1 through 10000, which have 8 in them such as 8, 68, 801, 8888, etc...
sumWithout8s is the sum of all the values that don't have 8s in them such as 1, 12, 242 etc...

Any algorithms for this ?  Reply With Quote

2. Member Join Date
Mar 2012
Location
Sweden
Posts
88
Rep Power
0 Re: Checking whether an integer value has a certain integer in it.

One way you could do it is convert the int into a string and check if the string contains the number 8 (String.contains("8")). If it does contain 8 then add one to the sum8 variable otherwise add to the other one. Or when the loop is done take the sum of all numbers and subtract the sum of the numbers with 8's in them.

It might not be the fastest or best way but it does the trick. (With this reply I'm expecting you to know how to get the sum of all the integers between 1 and 10000 if you don't post a reply).

PS. I'm not a programming pro.  Reply With Quote

3. Member Join Date
Oct 2013
Posts
13
Rep Power
0 Re: Checking whether an integer value has a certain integer in it.

yeah a simple for loop, thanks all i need to know  Reply With Quote

4. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
13 Re: Checking whether an integer value has a certain integer in it.

Iterative modular arithmetic mod 10 comes to mind.

Regards,
Jim  Reply With Quote

5. Re: Checking whether an integer value has a certain integer in it.

Duh, you don't need a for loop for the first sub-problem: the sum of the number 1+2+3+ ... +n == n*(n+1)/2; if you subtract the sum of all numbers with an 8 in it from this number you get the sum of all numbers wihout an 8 in it ... with a bit of trickery you don't need any for loops at all.

kind regards,

Jos  Reply With Quote Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•