zoukankan      html  css  js  c++  java
  • [LeetCode#246] Missing Ranges Strobogrammatic Number

    Problem:

    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.

    Analysis:

    This kind of problem is very very easy!!! Keep clam and carry on!
    Basic idea:
    1. identify which digits are valid for construct a Strobogrammatic Number.
    Instant idea: 0, 1, 8.
    Hint from the question: 6, 9
    private boolean isStroboDigit(Character c) {
        if (c == '0' || c == '1' || c == '6' || c == '8' || c == '9')
            return true;
        return false;
    }
    
    2. To look a num upside own is equal to reverse it. (with '6' change into '9', '9' change into '6')
    char c = num.charAt(i);
    if (isStroboDigit(c)) {
        if (c == '6')
            buffer.append('9');
        else if(c == '9')
            buffer.append('6');
        else 
            buffer.append(c);
    } else {
            return false;
    }
    
    My common mistakes in implementation:
    1. write : (forget to change i++ into i--, when realizing we should scan from the last charcter!)
    for (int i = len - 1; i >= 0; i--)
    into
    for (int i = len - 1; i >= 0; i++)
    
    
    2. return buffer.toString.equals(num);
    Forget () after toString method.

    Solution:

    public class Solution {
        public boolean isStrobogrammatic(String num) {
            if (num == null)
                throw new IllegalArgumentException("num is null");
            int len = num.length();
            if (len == 0)
                return true;
            StringBuffer buffer = new StringBuffer();
            for (int i = len - 1; i >= 0; i--) {
                char c = num.charAt(i);
                if (isStroboDigit(c)) {
                    if (c == '6')
                        buffer.append('9');
                    else if(c == '9')
                        buffer.append('6');
                    else 
                        buffer.append(c);
                } else {
                    return false;
                }
            }
            return buffer.toString().equals(num);
        }
        
        
        private boolean isStroboDigit(Character c) {
            if (c == '0' || c == '1' || c == '6' || c == '8' || c == '9')
                return true;
            return false;
        }
    }
  • 相关阅读:
    Mac上搭建Hadoop环境(3) — Hive下载及安装
    Mac上搭建Hadoop环境(2) — Hadoop下载及安装
    Mac上搭建Hadoop环境(1) — 虚拟机的安装及SSH免密设置
    Mac上ssh localhost免密失败该如何解决
    Java8 Lambda 之 Collection Stream
    Java 集合Collection——初学者参考,高手慎入(未完待续)
    Java注解Annotation(一)
    ubuntu下安装和破解navicat的方法
    java I/O流类概述
    List元素为泛型时的注意事项
  • 原文地址:https://www.cnblogs.com/airwindow/p/4796836.html
Copyright © 2011-2022 走看看