一道Tencent面试题

来源:互联网 发布:陈绮贞太阳知乎 编辑:程序博客网 时间:2024/04/30 16:31

小小+霸霸+王王=小霸王

用SQL列举出结果(下面是javaEye上的网友写的)

create table n_table (n int)

insert n_table values(1);//把1到9插入

 select a.n, b.n, c.n 
 from n_table a, n_table b, n_table c 
 where 11 * (a.n + b.n + c.n) = a.n * 100 + b.n * 10 + c.n 

 

相当java代码里面 三个 for 循环,或者 Y+10Z=89X,然后把符合条件的 输出。也有网友给出了 java代码。(这对我们程序员不算问题吧,这里就不列出)

 

个人想了下,单纯从这道题目来看,可不可以先分析下?

 

从题目可以得知 小霸王 的取值范围会在 100-297之间。我们不用循环判断,我们从 小霸王 往反向拆分

 

然后在拆分里面 加 符合上面条件的判断,这样循环应该减少很多次吧。个人没学过数据结构,只能这样写写。嘿嘿。

 

package test;

public class TQTest {

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        int maxValue = 297;
        int minVaule = 100;
        int temp1[] = null;
        for(int i = minVaule;i<=maxValue;i++)
        {
            temp1 = returnChangeValue(i);
            if(temp1!=null && temp1.length==3)
            {
                if(temp1[0]!=0 && temp1[1]!=0 && temp1[2]!=0)
                {
                    System.out.println(temp1[0]+"  "+temp1[1]+"  "+temp1[2]);
                }
            }
        }
    }
    private static int[] returnChangeValue(int temp)
    {
        int x,y,z;
        int value  = temp;
        x = temp/100;
        temp = temp%100;
        y = temp/10;
        temp = temp%10;
        z = temp;
        if(x+x*10+y*10+y+z*10+z == value)
        {
            return new int[]{x,y,z};
        }else
        {
            return new int[]{0,0,0};
        }
    }
}

 

感觉还是蛮局限的,没有提炼出通用的办法,纯粹为解决问题而写,数据结构白痴啊。

原创粉丝点击