Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function binaryToDecimal ($value) {
- if (gettype($value) !== 'string') {
- throw new InvalidArgumentException('Argument must be a string');
- }
- if (preg_match('/^[01]*$/', $value) !== 1) {
- throw new InvalidArgumentException('Argument must be a sequence of 1s and 0s');
- }
- $number = 0;
- for ($i = 0; $i < strlen($value); $i++) {
- $number *= 2;
- if ($value[$i] === '1') {
- $number += 1;
- }
- }
- return $number;
- }
- $testCases = [
- ['000', 0],
- ['001', 1],
- ['010', 2],
- ['011', 3],
- ['100', 4],
- ['101', 5],
- ['110', 6],
- ['111', 7],
- ];
- foreach ($testCases as [$input, $expected]) {
- echo "Testing '$input', expecting $expected: ";
- $actual = binaryToDecimal($input);
- if ($actual === $expected) {
- echo "OK\n";
- } else {
- echo "Failed, got $actual\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement