Skip to content

Instantly share code, notes, and snippets.

@minte9
Last active April 14, 2021 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minte9/961ea8515fa7221308212d05c290007a to your computer and use it in GitHub Desktop.
Save minte9/961ea8515fa7221308212d05c290007a to your computer and use it in GitHub Desktop.
Php / Basics / Integers / Decimal 2 Ocatal - https://www.minte9.com/php/basics-integers-13
<?php
/**
* Compose $m octal value using myFunc() recursively
* Use reminder and quontient values
*
* 97 (decimal) = 141 (octal)
* 97 % 8 => reminder 1
* 12 % 8 => reminder 4
* 1 % 8 => reminder 1
*
* 1*8^2 + 4*8^1 + 1*8^0 = 64 + 32 + 1 = 97
*/
function myFunc($no) {
/**
* SOLUTION
*/
if ($no == 0) return NULL;
$m = $no%8; // reminder
$q = (int) $no/8; // quontient
$m = myFunc($q) . $m;
return (int) $m;
}
// TESTS
{
foreach([7=>7, 8=>10, 10 => 12, 97 => 141] as $k=>$v) {
if (myFunc($k) != $v) throw new Exception($k . " failed");
if (decoct($k) != $v) throw new Exception($k . " failed");
}
echo "Tests passed!";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment