C++零基础算法100题-速算机器人

76 阅读1分钟

题目链接: LCP 17. 速算机器人 - 力扣(LeetCode)

题目描述

image.png

解题思路

  1. 首先遍历这个字符串
  2. 如果说遍历到的字符串为A,那么走x=x*2+y
  3. 如果说遍历到的字符串为B,那么走y=y*2+x
  4. 将x+y返回回去

解题步骤

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