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;
        }
    }
  • 相关阅读:
    telnet退出
    Eclipse srever起来时,时间超过45s。
    maven报错 Failure to transfer org.apache.maven.plugins:maven-compiler-plugin:pom:3.5.0 from
    需求讨论
    PyTorch学习笔记之计算图
    PyTorch学习笔记之CBOW模型实践
    PyTorch学习笔记之n-gram模型实现
    PyTorch学习笔记之初识word_embedding
    7月3日-9日_周报
    python学习笔记之heapq内置模块
  • 原文地址:https://www.cnblogs.com/airwindow/p/4796836.html
Copyright © 2011-2022 走看看