Last active
April 14, 2021 08:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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