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

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

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.

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

相关推荐
山峰哥2 分钟前
现代 C++ 的最佳实践:从语法糖到工程化思维的全维度探索
java·大数据·开发语言·数据结构·c++
CoderYanger2 分钟前
动态规划算法-两个数组的dp(含字符串数组):43.不同的子序列
java·算法·leetcode·动态规划·1024程序员节
Xの哲學3 分钟前
Linux I3C驱动深度剖析: 从原理到实战的全面解析
linux·服务器·算法·架构·边缘计算
秦苒&12 分钟前
【C语言指针一】从入门到通透:核心知识点全梳理(内存、变量、运算、const修饰)
c语言·开发语言·c++
蓑衣夜行15 分钟前
QtWebEngine 自动重启方案
开发语言·c++·qt·web·qwebengine
爱喝热水的呀哈喽17 分钟前
chns方程 推导简单的能量耗散律,分部积分向量形式,sav初简介
算法
Source.Liu17 分钟前
【LibreCAD】点实体源码解析
c++·qt·cad
代码游侠19 分钟前
应用——统计文件字符数、单词数、行数
服务器·笔记·算法
岁岁的O泡奶25 分钟前
NSSCTF_crypto_[MTCTF 2021 final]ezRSA
经验分享·python·算法·密码学·crypto
煤球王子42 分钟前
学而时习之:C++中的标准模板库7
c++