[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;
    }
}
原文地址:https://www.cnblogs.com/airwindow/p/4796836.html