机器人能否回到原点 - 简单

*************

C++

topic:657. 机器人能否返回原点 - 力扣(LeetCode)

*************

inspect the topic very first.

|----------------------------------------------------------------------------|
| |

It is letters to decide which side the robot moves. And my thought is quite sample. Assumeing the robot can move back to the origin, then the numbers of L have to be the same with the numbers of R. So are U and D.

Then the code can be easy to write. Travel through the string and count the letters.

cpp 复制代码
class Solution {
public:
    bool judgeCircle(string moves) {
        
        int n = moves.size(); // to figure out the size at first
        int countR = 0;
        int countL = 0;
        int countU = 0;
        int countD = 0;

        for (int i = 0; i < n; i++)
        {
            if (moves[i] == 'R')
            {
                countR = countR + 1;
            }
            else if (moves[i] == 'L')
            {
                countL = countL + 1;
            }
            else if (moves[i] == 'U')
            {
                countU = countU + 1;
            }
            else
            {
                countD++;
            }
        }

        if (countR == countL && countD == countU)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

|----------------------------------------------------------------------------|
| |

However, I donot think it is a elegent code. If you gays finish the Nine-year compulsory education,you will know coordinate system.

|-----------------------------------------------------------------------------|
| |

↑ y = y + 1;

↓ y = y - 1;

← x = x - 1;

→ x = x + 1;

cpp 复制代码
class Solution {
public:
    bool judgeCircle(string moves) {
        int x = 0;
        int y = 0;

        for (char c : moves) 
        {
            if (c == 'U') y++;
            else if (c == 'D') y--;
            else if (c == 'R') x++;
            else if (c == 'L') x--;
        }
        
        return x == 0 && y == 0;
    }
};

|----------------------------------------------------------------------------|
| |

It is do elegent.

Maybe apple would change the design of ios in the near future. I donot care whether the ios system is fluently or not, I just want to see what desigh looks.

|----------------------------------------------------------------------------|
| |

相关推荐
元亓亓亓12 分钟前
LeetCode热题100--240.搜索二维矩阵--中等
算法·leetcode·矩阵
阿沁QWQ20 分钟前
单例模式的两种设计
开发语言·c++·单例模式
六bring个六28 分钟前
qtcreater配置opencv
c++·qt·opencv·计算机视觉·图形渲染·opengl
qwertyuiop_i33 分钟前
pe文件二进制解析(用c/c++解析一个二进制pe文件)
c语言·c++·pe文件
明月看潮生1 小时前
青少年编程与数学 02-019 Rust 编程基础 09课题、流程控制
开发语言·算法·青少年编程·rust·编程与数学
oioihoii1 小时前
C++23 views::slide (P2442R1) 深入解析
linux·算法·c++23
yxc_inspire1 小时前
基于Qt的app开发第八天
开发语言·c++·qt
yuhao__z2 小时前
代码随想录算法训练营第六十三天| 图论9—卡码网47. 参加科学大会,94. 城市间货物运输 I
算法·图论
June`2 小时前
专题三:穷举vs暴搜vs深搜vs回溯vs剪枝(全排列)决策树与递归实现详解
c++·算法·深度优先·剪枝
vlln2 小时前
适应性神经树:当深度学习遇上决策树的“生长法则”
人工智能·深度学习·算法·决策树·机器学习