Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the hexadecimal number system numbers are represented using 16 different digi

ID: 3870533 • Letter: I

Question

In the hexadecimal number system numbers are represented using 16 different digits:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

The hexadecimal number AF when written in the decimal number system equals 10x16+15=175.

In the 3-digit hexadecimal numbers 10A, 1A0, A10, and A01 the digits 0,1, and A are all present.

Like numbers written in base ten we write hexadecimal numbers without leading zeroes.

1) Write a PHP program with a function that given a value $n in input counts how many different number exist with all of the digits 0,1, and A present at least once for hexadecimal values from 1 to $n digits.

2) Add comments, checks and test cases in addition to the code.

Explanation / Answer

<?php
function writeMsg($number)
{
    $count=0;
   for($i=26;$i<=$number;$i++)//start from 26 because decimal rep of a hex number less than 26 does not contain 0,1,a
   {
       $string = dechex ($i);//obtain string representation of decimal number
      
       if(strpos($string, '1') !== false && strpos($string, 'a') !== false)//check if hex representation contains 1,a . didnt check for 0 because all numbers contain leading zeros
       {
           //echo $string.PHP_EOL;
           $count++;
       }  
   }
   echo $count;
}
$number = 161;
writeMsg($number); //call the function

?>

test cases:

$number =0 , expected output=0

$number=26,expected output=1

$number=161,expected output=2

-----------------------------------------------------------------------------------------------------------------

myMsg

function myMSg($n)
{
$i=26;
$string = dechex($i);
while(strlen($string)<= $n)
{
  
   if(strlen($string)==2)
   {
       if(strpos($string, '1') !== false && strpos($string, 'a') !== false)//check if hex representation contains 1,a . didnt check for 0 because all 2 digit numbers contain leading zeros
       {
           echo $string.PHP_EOL;
           //$count++;
       }
   }
   else
   {
       if(strpos($string, '1') !== false && strpos($string, 'a') !== false && strpos($string,'0')!=false)//check if hex representation contains 1,a,0
       {
           echo $string.PHP_EOL;
           //$count++;
       }
   }
   $i++;
   $string = dechex($i);
}
//echo $count;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote