题解:1056. 易混淆数:数学模拟

一、题目描述:

给定一个数字 N,当它满足以下条件的时候返回 true:

原数字旋转 180° 以后可以得到新的数字。

如 0, 1, 6, 8, 9 旋转 180° 以后,得到了新的数字 0, 1, 9, 8, 6 。

2, 3, 4, 5, 7 旋转 180° 后,得到的不是数字。

易混淆数 (confusing number) 在旋转180°以后,可以得到和原来不同的数,且新数字的每一位都是有效的。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/confusing-number
二、解题思路:

三、代码实现:两种写法

class Solution {

    /**
     * @param Integer $n
     * @return Boolean
     */
    function confusingNumber($n) {
        //原数字旋转180 合法为 旋转后的数字 或则不合法为-1 映射
      //原数字=k 0 1  2  3  4  5 6  7 8 9
        $map = [0,1,-1,-1,-1,-1,9,-1,8,6];
        $m = $n;//复制一份 方便循环操作
        $newnum =0;
        while($m>0){
            $last = $m%10;//从低位到高位判断每一位合法否
            //不合法
            if($map[$last]<0){
                return false;
            }
            //合法 翻转
            $newnum = $newnum * 10 +$map[$last];
            $m = intval($m/10);
        }
        return $newnum != $n;
    }
    function confusingNumber1($n) {
        $valid = [0=>0,1=>1,6=>9,8=>8,9=>6];
        $invalid = [2=>1,3=>1,4=>1,5=>1,7=>1];
        $arr = str_split($n);//将数字字符转成列表
        $len = count($arr);
        $newnum = "";
        for($i=0;$i<$len;$i++){
            //如果数字不合法停止
            if(isset($invalid[$arr[$i]])){
                return false;
            }
            //合法拼接成新的数字
            $newnum .= $valid[$arr[$i]];
        }
        $m = strrev($n);//原数字翻转
        return $m!=$newnum;//和新数字对比 不同则为结果
        
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值