A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
思路:写一个rotate函数,输入是0-9,输出是旋转后的数字。若旋转后不是数字,则输出一个‘X‘。
在主函数中,我们要检查的数字是string类型,用left和right两个指针从两端向中间逐个比较。用roate函数计算left所指的数字旋转后的结果并与right所指的数字进行比较。若不相同则为false。
class Solution { public: char rotate(char c) { if (c == ‘6‘) return ‘9‘; else if (c == ‘9‘) return ‘6‘; else if (c == ‘0‘ || c == ‘1‘ || c == ‘8‘) return c; else return ‘X‘; } bool isStrobogrammatic(string num) { int left = 0, right = num.size() - 1; while (left <= right) { if (rotate(num[left]) != num[right]) return false; left++; right--; } return true; } };
时间: 2024-12-09 09:08:04