zoukankan      html  css  js  c++  java
  • Strobogrammatic Number -- LeetCode

    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;
        }
    };
  • 相关阅读:
    我要变牛逼
    java web
    导师选择
    2.1进程
    来到博客园写东西的第一天
    简单的页面布局
    html5
    第一个servlet程序
    java2D
    字节流 文件字节流 缓冲字节流
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5767495.html
Copyright © 2011-2022 走看看