drdyszuy488152 2012-11-07 19:12
浏览 68
已采纳

反转数字拼图

I'm are trying to teach myself to be better at programming. Part of this I have been taking puzzle that I find in newspapers and magazines and trying to find programming solutions

Today I seen a puzzle regarding numbers that are the reversed when multiplied by a number from 2-9. The example given was 1089 * 9 = 9801.

I have started to write a program in php to find the numbers this applies to and adds them to an array.

First I created a loop to cycle through the possible numbers. I then reversed each of the numbers and created a function to compare the numbered and the reversed number. The function then returns numbers that meet the criteria and adds them to an array.

This is what I have so far...

<?php

        function mul(){ // multiply number from loop

            for($i=2;$i<=9;$i++){

                $new = $num * $i;

                    if($new == $re){
                    return $new;    
                    }
                    else{
                    return;
                    }
            }
        }

        $arr =  array();

        for ($num = 1000; $num <10000; $num++) { //loop through possible numbers

                      $re =  strrev($num); // get reverse of number
                      func($re,$num); //multiply number and return correct numbers
                      $arr.push($new); //add to array??
         }
 ?>

I'm still very new to php and I find understanding programming, any pointers on a more logical way of doing this puzzle would be greatly appreciated.

  • 写回答

3条回答 默认 最新

  • doubaolan2842 2012-11-07 19:18
    关注

    Here's my solution with a nested loop. Quick and dirty.

    $result = array();
    for ($i = 1000; $i < 5000; $i++) {
        for ($m = 2; $m < 10; $m++) {
            if ($i*$m == (int)strrev($i)) {
                $result[] = array($i, $m);
            }
        }
    }
    var_dump($result);
    

    I'd like to expand on this line:

    if ($i*$m == (int) strrev($i)) {
    

    One side is $i*$m, easy, the multipication.

    On the other, we have (int)strrev($i), which means "Take $i, cast it to a string, and reverse that. Then cast it back into an int.

    If that evaluates to true, an array containing $i and m is inserted into the $result array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案