1. 程式人生 > >LeetCode-Rotated Digits

LeetCode-Rotated Digits

Description: X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

Now given a positive number N, how many numbers X from 1 to N are good?

Example:

Input: 10
Output: 4

Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9. Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.

Note:

N  will be in range [1, 10000].

題意:給定一個整數N,判斷再範圍[1,N]內有幾個好數字,其定義是將這個數的每一位旋轉180°後所組成的數字與原來的數字不相同,並且旋轉後的這個數是合法的;

  • 0、1、8旋轉後依然是自身
  • 2、5、6、9旋轉後是5、2、9、6
  • 其他的數字旋轉後是非法的

解法:我們應該先定義一個旋轉後的數字表用於此後的判斷是否合法;之後我們可以遍歷範圍[1,N]內的數字,將這個數字每一位進行旋轉後如果是非法的那麼直接返回false;否則我們累加這個數用於判斷最後旋轉得到的數字與原數字是否不同;

Java
class Solution {
    public int rotatedDigits(int
N) { int[] rotateNum = new int[] {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; int cnt = 0; for (int i = 1; i <= N; i++) { cnt = isGoodNum(rotateNum, i) ? cnt + 1 : cnt; } return cnt; } private boolean isGoodNum(int[] rotateNum, int x) { int num = 0; int order = 1; int key = x; while (x > 0) { if (rotateNum[x % 10] == -1) { return false; } num += order * rotateNum[x % 10]; order *= 10; x /= 10; } return num == key ? false : true; } }