地址:https://leetcode-cn.com/problems/nGK0Fy/
<?php /** LCP 17. 速算機器人 小扣在秋日市集發現了一款速算機器人。店家對機器人說出兩個數字(記作 x 和 y),請小扣說出計算指令: "A" 運算:使 x = 2 * x + y; "B" 運算:使 y = 2 * y + x。 在本次遊戲中,店家說出的數字爲 x = 1 和 y = 0,小扣說出的計算指令記作僅由大寫字母 A、B 組成的字符串 s,字符串中字符的順序表示計算順序,請返回最終 x 與 y 的和爲多少。 示例 1: 輸入:s = "AB" 輸出:4 解釋: 經過一次 A 運算後,x = 2, y = 0。 再經過一次 B 運算,x = 2, y = 2。 最終 x 與 y 之和爲 4。 提示: 0 <= s.length <= 10 s 由 'A' 和 'B' 組成 */ class Solution { /** * @param String $s * @return Integer */ function calculate($s) { return 2**strlen($s); } function calculate1($s) { $x = 1; $y = 0; for ($i = 0,$count = strlen($s);$i < $count;$i++){ if ($s[$i] == 'A'){ $x = 2 * $x + $y; }elseif ($s[$i] == 'B'){ $y = 2 * $y + $x; } } return $x +$y; } }