面試題 17.01. 不用加號的加法

地址:https://leetcode-cn.com/problems/add-without-plus-lcci/

<?php
/**
 * Created by PhpStorm.
 * User: huahua
 * Date: 2020/10/13
 * Time: 下午1:33
面試題 17.01. 不用加號的加法
設計一個函數把兩個數字相加。不得使用 + 或者其他算術運算符。

示例:

輸入: a = 1, b = 1
輸出: 2


提示:

a, b 均可能是負數或 0
結果不會溢出 32 位整數
 */
class Solution {

    /**
     * @param Integer $a
     * @param Integer $b
     * @return Integer
     */
    function add($a, $b) {
        $sum = $a;
        while($b){
            $sum = $a ^$b;
            $b = ($a & $b) << 1;
            $a = $sum;
        }
        return $sum;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章