算法实践

1. PHP实现从1累加到100(1+2+….+100=)的几种思路?

function sum1($num)
{
    if ($num > 0) {
        return $num + sum1($num - 1);
    }

}

$a = sum1(100);
echo $a;

function sum2($num)
{
    $sum = 0;
    for ($i = 1; $i <= $num; $i++) {
        $sum += $i;
    }
    return $sum;
}

$a = sum2(100);
echo $a;

function sum3($num)
{
    $sum = 0;
    while ($num > 0) {
        $sum += $num;
        $num--;
    }
    return $sum;
}

$a = sum3(100);
echo $a;

echo array_sum(range(1, 100));

2. PHP 链式操作

class DB
{
    public function __construct()
    {

    }

    public function select()
    {
        return $this;
    }

    public function where()
    {
        return $this;
    }

    public function limit()
    {
        return $this;
    }


    public function orderBy()
    {
        return $this;
    }    
}

$db = new DB();

$db->select()->where()->limit()->orderBy();

3. 斐波那契数列

递归
function recursive($n)
{
    if($n == 0 || $n == 1) return $n;
    return sum($n-1) + sum($n-2); 
}
迭代
function iteration($n)
{
    $n0 = 0;
    $n1 = 1;

    $res = 0;
    for ($i = 2; $i <= $n; $i++) { 
        $res = $n0+$n1;
        $n0 = $n1;
        $n1 = $res;
    }
    return $res;
}

4. 两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8

class ListNode {
    public $val = 0;
    public $next = null;
    function __construct($val) { $this->val = $val; }
}
class Solution {
    /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    public function addTwoNumbers($l1, $l2)
    {
        $current = null;
        $num = 0;
        do{

            $val = $l1->val + $l2->val + $num;
            if($val < 10){ $num = 0;}
            if($val >= 10){ $val -= 10;$num = 1;}

            $node = new ListNode($val);
            if($current)
            {
                $next->next= $node;
            }else{
                $current = $node;
            }

            $next = $node;

            $l1 = $l1->next;
            $l2 = $l2->next;

        }while ($l1 || $l2 || $num);
        return $current;
    }
}

results matching ""

    No results matching ""

    results matching ""

      No results matching ""