projecteuler#1 Multiples of 3 and 5

* Solution.php

<?php
/**
 * Problem#1
 * https://projecteuler.net/problem=1
 * If we list all the natural numbers below 10 that are multiples of 3 or 5,
 * we get 3, 5, 6 and 9. The sum of these multiples is 23.
 * Find the sum of all the multiples of 3 or 5 below 1000.
 */
class Solution {

    protected $bound;

    public function __construct($bound) {
        $this->bound = $bound;
    }

    public static function int2digitArray(int $num) : array {
        $a = [];
        while ($num > 0) {
            $digit = $num % 10;
            array_unshift($a, $digit);
            $num = floor($num / 10);
        }
        return $a;
    }

    public static function isMultipleOf3(array $a) : bool {
        $sum = array_reduce($a, function($sum, $cur) {
            $sum += $cur;
            return $sum;
        }, 0);
        return $sum % 3 === 0;
    }

    public static function isMultipleOf5(array $a) : bool {
        $last = $a[count($a)-1];
        return $last === 0 || $last === 5;
    }

    public function sumAll() : int {
        $sum = 0;
        for ($i = 3; $i < $this->bound; $i++) {
            $a = self::int2digitArray($i);
            if (self::isMultipleOf3($a) || self::isMultipleOf5($a)) {
                $sum += $i;
            }
        }
        return $sum;
    }
}

$solution = new Solution(1000);
echo $solution->sumAll().PHP_EOL;  // 233168

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/82941795