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;
        }
    }
  • 相关阅读:
    使用AOP 实现Redis缓存注解,支持SPEL
    springmvc 双亲上下文导致的 No mapping found for HTTP request
    调用iframe 中的js[兼容各种浏览器]
    NIO学习:异步IO实例
    byte数组与对象之间的相互转换
    NIO学习:buffer读入与写出(文件复制示例)
    NIO学习:使用Channel、Buffer写入文件
    使用摘要流获取文件的MD5
    ActiveMQ入门实例
    获取java项目 classpath目录
  • 原文地址:https://www.cnblogs.com/airwindow/p/4796836.html
Copyright © 2011-2022 走看看