出自国外某牛人的一道面试题(About 42)

来源:互联网 发布:软件行业 技术规范 编辑:程序博客网 时间:2024/05/01 19:07

首先,这道题并不难,但是也不简单。

  • Problem

    Write some code that calculates how many numbers under a million (positive integers) have digits that add up to 42.

这是来自于国外某大牛的blog提到的一道面试题。作者先是在文中慨叹了人类在招聘软件开发人员时的极度无奈,接着表达了对诸如FizzBuzz(我也做过)类型的面试题的不满,最后,提出了适合作为面试题目的类型,比如这一道(不过,作者表示今后并不会在面试中问及)。

作者表示,曾经在Twitter上问到过这个问题,并很快得到了不少不错的答案。(读到此处,忍不住想自己动手实现一下。可是经过思考后,发现我那可怜的数据结构与算法基础并不足以给出高效的快速方法。算了,先不管不了,能实现了再说。于是,诞生了如下代码)

  • My Solution
public class DigitsSum {    public static void main(String[] args) {        int count= 0;        for (int i = 0; i < 1000000; i++) {            char[] ch = (i + "").toCharArray();            int sum = 0;            for (int j = 0; j < ch.length; j++) {                // Method 1: char to int                // sum += Integer.parseInt(ch[j] + "");                // Method 2: Actually, char is int!                sum += ch[j] - '0';            }            if(sum == 42) {                count++;            }        }        System.out.println(count);    }}

之后,看了下作者blog上贴出的几个回复者的代码实现(不同语言),乍一看,尼玛,开玩笑呢,怎么都这么短! 瞬间感觉人家好牛逼……
看到有Python、Java版的,然后主要瞅了一眼Java版的,先来看一眼:

  • Solution
    Original Source of 42

其实,那些回复者为了使代码尽可能的短,穷尽了其一切技能呀,我调了下格式,稍作了下改动,方便阅读:

class S {    public static void main(String a[]) {        int i = 0;        int j = 0;        for(; i++ < 1e6; j += (i+"").chars().map(x->x-48).sum() == 42 ? 1 : 0);        System.out.print(j);    }}
  • Note
    1. chars()是继承自接口CharSequence的一个方法,其返回值为IntStream类型;
    2. IntStream有一个map()方法;
    3. map()使用了lambda表达式,使得语句精简;
    4. 又用到IntStream的一个名为sum()的方法,求和;
    5. 最后采用三目运算符,使语句更简短。

仔细看完会发现:这也是笨办法!!!
实际上,通过与自己写的“笨办法”的代码相比,这样写反而耗时更长(代码段前后分别加入long timeStart = System.currentTimeMillis();以及long timeEnd = System.currentTimeMillis();,最后计算时间差)。另外,因为最小的满足条件的数是69998,即令i = 69998;不过,经过测试,发现这样做,整体时间并没多少变化,好奇怪……

  • Conclusion

However,人家的Niubility在哪里呢?感觉对其来说,Java API 文档就像自己的左右手一样,随便就拈来,我等目前是望尘莫及啊,仍需修炼……

  • PS

原作者在LinkedIn上的资料:

Small-time investorFormer CEO of IndexTankSoftware EngineerProduct Creator

Goals: too many to list. In general, to tackle problems that have these characteristics:

technology is necessary to solve it.there is a business case for solving it.solving it will improve people's lives.

很欣赏作者的goals,看写得多诚恳,崇拜ing,感谢作者!


If you have any questions or any bugs are found, please feel free to contact me.

Your comments and suggestions are welcome!

0 0