首页 > 其他 > 详细

Strobogrammatic Number -- LeetCode

时间:2016-08-13 11:16:07      阅读:118      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

Strobogrammatic Number -- LeetCode

原文:http://www.cnblogs.com/fenshen371/p/5767495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!