PU Strobogrammatic Number

Jan 01, 1970

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.

Example:

  • the numbers "69", "88", and "818" are all strobogrammatic.

C Solution 1:

bool isStrobogrammatic(char* num) {
    char *end = num + strlen(num) - 1;
    while (num <= end) {
        if (*num == *end) {
            if (*num == '0' || *num == '1' || *num == '8') {
                num++;
                end--;
                continue;
            }
            return false;
        }
        if (*num == '6' && *end == '9' || *num == '9' && *end == '6') {
            num++;
            end--;
            continue;
        }
        return false;
    }
    return true;
}

C Solution 2:

bool isStrobogrammatic(char* num) {
    char flag[256] = {0};
    flag['6'] = '9';
    flag['9'] = '6';
    flag['0'] = '0';
    flag['1'] = '1';
    flag['8'] = '8';

    char *l = num, *r = strlen(num) + num - 1;
    for (; l <= r && flag[*l] == *r && flag[*r] == *l; l++, r--);
    return l > r;
}

Summary:

  1. nothing special.
  2. 0ms, 0%.

LeetCode: 246. Strobogrammatic Number