Exemplo n.º 1
0
/**
 * Problem: The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
 *
 * Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
 *
 * (Please note that the palindromic number, in either base, may not include leading zeros.)
 *
 * Solution: 
 */
include "helper.php";
function isPalindromic($num)
{
    $digits = str_split($num);
    $len = count($digits);
    for ($i = 0; $i < floor($len / 2); $i++) {
        if ($digits[$i] != $digits[$len - $i - 1]) {
            return false;
        }
    }
    return true;
}
$total = 0;
for ($i = 1; $i < 1000000; $i++) {
    if (isPalindromic($i)) {
        if (isPalindromic(decbin($i))) {
            $total += $i;
        }
    }
}
result(872187, $total);
Exemplo n.º 2
0
        throw new \InvalidArgumentException('$integer must be a number');
    }
    $integer = (int) $integer;
    if ($integer < 0) {
        return false;
    }
    if ($integer === 0) {
        return true;
    }
    $numberOfDigits = floor(log10($integer)) + 1;
    $integerRemaining = $integer;
    $msdShift = pow(10, $numberOfDigits - 1);
    for ($i = 0; $i < $numberOfDigits / 2; $i++) {
        if ((int) ($integer / $msdShift) != (int) ($integerRemaining % 10)) {
            return false;
        }
        $integer %= $msdShift;
        $msdShift /= 10;
        $integerRemaining /= 10;
    }
    return true;
}
$inputHelper = new InputHelper();
$integer = $inputHelper->readInputFromStdIn('Enter the integer to test: ');
$result = isPalindromic($integer);
if ($result === true) {
    printf('The integer %d is palindromic', $integer);
} else {
    printf('The integer %d is not palindromic', $integer);
}
print PHP_EOL;