LeetCode 788. 旋轉數字(C++、python)
阿新 • • 發佈:2018-12-14
我們稱一個數 X 為好數, 如果它的每位數字逐個地被旋轉 180 度後,我們仍可以得到一個有效的,且和 X 不同的數。要求每位數字都要被旋轉。
如果一個數的每位數字被旋轉以後仍然還是一個數字, 則這個數是有效的。0, 1, 和 8 被旋轉後仍然是它們自己;2 和 5 可以互相旋轉成對方;6 和 9 同理,除了這些以外其他的數字旋轉以後都不再是有效的數字。
現在我們有一個正整數 N
, 計算從 1
到 N
中有多少個數 X 是好數?
示例: 輸入: 10 輸出: 4 解釋: 在[1, 10]中有四個好數: 2, 5, 6, 9。 注意 1 和 10 不是好數, 因為他們在旋轉之後不變。
注意:
N 的取值範圍是 [1, 10000]
C++
class Solution { public: int rotatedDigits(int N) { int count=0; int countpos; int countneg; int temp; int mod; for(int i=1;i<=N;i++) { countpos=0; countneg=0; temp=i; while(temp) { mod=temp%10; if(mod==4 || mod==7 || mod==3) { break; } else { if(mod==2 || mod==5 || mod==6 || mod==9) { countpos++; } } temp/=10; } if(temp==0 && countpos>0) { count++; } } return count; } };
python
class Solution: def rotatedDigits(self, N): """ :type N: int :rtype: int """ count=0 for i in range(1,N+1): temp=i countpos=0 countneg=0 while temp: mod=temp%10 if mod==3 or mod==4 or mod==7: break else: if mod==2 or mod==5 or mod==6 or mod==9: countpos += 1 temp//=10 if temp==0 and countpos>0: count += 1 return count