【LeetCode】788. Rotated Digits

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.

题目大意:给定一个数,翻转其每一位数,仍然可以成为一个有效的数字,而且不与原来的数重复,我们认为这个数是一个好数,求给定区间内好数的数目。

分析: 对于每一个数来说,我们假设数子为abcd,可以将数子拆分为abc,d两部分。如果abc翻转完后还是abc,d翻转完后还是d,那么abcd翻转完后与原来的数一致,当abc,d两部分只有任意一个翻转后不是有效数字,abcd就翻转后就无效,只要有一个出现翻转后有效,那么abcd就可以称为好数。因此我们可以使用动态规划进行解题。

建立状态转移方程:

建立dp[n+1],0 为无效,1为翻转后仍为原数,2表示翻转后与原数不同 。

dp[i] : 将有dp[i/10] 和dp[i%10]共同决定。

 

代码:

 int dp[] = new int[N+1];
		 int res = 0;
		 for(int i = 0 ; i < N+1;i++) {
			 if(i < 10) {
				 if (i == 0 || i == 1 || i == 8) dp[i] = 1;
				 else if(i == 2 || i == 5 || i == 6 || i == 9) {
					 res++;
					 dp[i] =2;
				 }
			 }else {
				 int a = dp[i/10],b = dp[i%10];
				 if(a == 1 && b == 1) dp[i] = 1;
				 else if((a >1 && b >=1) ||( b >1 && a>=1)) {
					 dp[i] = 2;
					 res++;
				 }
			 }
		 }
		 return res;

当然还可以直接暴力循环,将每一位数字转为字符串,然后逐个验证就行。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值