Strobogrammatic Number

246. Strobogrammatic Number

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.

public class Solution {
    public boolean isStrobogrammatic(String num) {
        if (num == null || num.length() == 0) {
            return true;
        }
        
        int i = 0, j = num.length() - 1;
        
        while (i <= j) {
            char c1 = num.charAt(i), c2 = num.charAt(j);
            
            if (c1 == c2) {
                if (c1 != '0' && c1 != '1' && c1 != '8') {
                    return false;
                }
            } else {
                if (!(c1 == '6' && c2 == '9') && !(c1 == '9' && c2 == '6')) {
                    return false;
                }
            }
            
            i++;
            j--;
        }
        
        return true;
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge