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:
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,判断再范围[1,N]内有几个好数字,其定义是将这个数的每一位旋转180°后所组成的数字与原来的数字不相同,并且旋转后的这个数是合法的;
- 0、1、8旋转后依然是自身
- 2、5、6、9旋转后是5、2、9、6
- 其他的数字旋转后是非法的
解法:我们应该先定义一个旋转后的数字表用于此后的判断是否合法;之后我们可以遍历范围[1,N]内的数字,将这个数字每一位进行旋转后如果是非法的那么直接返回false;否则我们累加这个数用于判断最后旋转得到的数字与原数字是否不同;
Java