LCP 17. 速算机器人

仅供自己学习

思路:
直接遍历判断即可

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

另一种数学公式来求解
当为"A"时,结果为x+y=2x+y+y
当为"B"时,结果为x+y=2
y+x+x
那么就是 x+y=2y+2x,相当于每遇到一个A或B,x+y的值都会增加一倍,那么s有多长,结果就为2的s长度次方,s长度为n,x+y就是2^n。

class Solution {
public:
    int calculate(string s) {
        if(s.length()==0) return 1;
        return pow(2,s.length());
    }
};
posted @ 2021-04-03 22:46  Mrsdwang  阅读(58)  评论(0编辑  收藏  举报