Dahab
Dahab

Reputation: 514

PHP: Generate ordered IDs that has no zeros and ones

I want to create ordered numbers from 2 to whatever with no zero's and ones.

e.g 1, 10, 11, 15, 41, 50, 60, 61, etc these are invalid number

My try:

for($i=0, $ii=1000; $i<$ii; $i++){
     if($i%11){
        continue;
     }
}

but this does not work

Upvotes: 0

Views: 45

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134045

Generate an integer, convert it to an octal string, and then increase the value of each digit by 2. I'm not a PHP programmer, so I'll give you the pseudocode.

foo = 1
octFoo = decoct(foo)
// at this point, octFoo is equal to 1

// Now go through each character in octFoo and increase it by 2.
// So 0 becomes 2, 1 becomes 3, etc.

Given the number 8, octFoo would be 10, and the final result would be 32.

You could do this without the intermediate octal step if you wanted to write your own integer-to-string routine. Rather than using the digits 0 through 7, use the digits 2 through 9.

Upvotes: 0

maxhb
maxhb

Reputation: 8865

You can treat the numbers as strings and search for the chars "0" and "1".

<?php
for($i=0; $i<100; $i++){
  if(strpos((string) $i, '0') !== false) continue; // contains 0
  if(strpos((string) $i, '1') !== false) continue; // contains 1

  echo $i . "\n";
}

Please note that strpos() returns the position of the first occurence of the search string (aka needle) within the given string (aka haystack) or false if no match is found. This is why you have to compare the result of strpos() with !== false as a result of 0 would be considered to be false too if just using == false.

See http://php.net/manual/en/function.strpos.php for a detailed documentation with examples.

Upvotes: 2

Related Questions