LeetCode LCP 17. Quick Calculation Robot

topic

Xiaokou found a quick calculation robot in the autumn market. Stores the robot say two numbers (denoted as xand y), please say small deduction calculation instruction:

  • "A" Operation: make x = 2 * x + y;
  • "B"Operation: make y = 2 * y + x。

In this game, a digital store is spoken x = 1and y = 0computing instructions, referred to as small buckle spoken only uppercase letters A, Ba string consisting of sthe sequence of characters in a string indicating the calculated order, finally returned xto yand is How many.

Example 1:

输入:s = "AB"

输出:4

解释:
经过一次 A 运算后,x = 2, y = 0。
再经过一次 B 运算,x = 2, y = 2。
最终 x 与 y 之和为 4。

prompt:

  • 0 <= s.length <= 10
  • sIt made 'A'and 'B'make up

Source: LeetCode
Link: https://leetcode-cn.com/problems/nGK0Fy
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

answer

class Solution {
    
    
    public int calculate(String s) {
    
    
        int x =1,y = 0;
        for(int i = 0;i < s.length(); i ++) {
    
    
            if(s.charAt(i) == 'A') {
    
    
                x = 2 * x + y;
            } else {
    
    
                y = 2 * y + x;
            }
        }
        return x + y;
    }
}

0ms 37.7MB


Click here for more solutions

Guess you like

Origin blog.csdn.net/lolly1023/article/details/108580059