JAVA面试题

最近面试遇到笔试题。

1、求1000的阶乘结果尾部0的个数。

解法:计算可分解5的个数
这种想法认为,1000! = 1000*999*...*1,而5*2= 10,故只要将所有的从1到1000的数分解成(2,5)组合,就可以知道尾数0的个数。同时,很显然,2的个数比5的个数要多,因此只需要关注5的分解的个数。

package com.tk.demos;

public class Test {
    public static void main(String[] args) {
        int c = new Test().test(1000);
        System.out.println(c);

    }

    public int test(int total) {
        int count = 0;
        for (int i = 5; i <= total; i++) {

            int tmp = i;
            while (tmp % 5 == 0) {
                count++;
                tmp = tmp / 5;
            }
        }
        return count;
    }
}

在网上找到的另外的解法:

通过分类统计计算

里面有:

625 的倍数:1个 (625*16)

125的倍数:8-1 = 7 (去掉625)

25的倍数:40-8 = 32 (去掉上面的7+1)

5的倍数:200-40 = 160 (去掉上面的32+7+1)

共: 1*4+7*3+32*2+160=249个0

2、假设类似"aba"、"aab"字符串相等,编写方法判断任意给定的两组字符串相等。

package com.tk.demos;

public class Test {
    public static void main(String[] args) {
        boolean test = new Test().strEquals("ab", "aba");
        System.out.println(test);
    }

    public boolean strEquals(String strOne, String strTwo) {
        if (strOne == null && strTwo == null) {
            return true;
        }
        if (strOne == null || strTwo == null) {
            return false;
        }
        if (strOne.length() != strTwo.length()) {
            return false;
        }
        return sort(strOne).equals(sort(strTwo));
    }

    public String sort(String strIn) {
        char[] s1 = strIn.toCharArray();
        for (int i = 0; i < s1.length; i++) {
            for (int j = 0; j < i; j++) {
                if (s1[i] < s1[j]) {
                    char temp = s1[i];
                    s1[i] = s1[j];
                    s1[j] = temp;
                }
            }
        }
        return String.valueOf(s1);
    }
}

3、如果在 try 语句块里使用 return 语句,那么 finally 语句块还会执行吗?

答案:会

这道题答案很简单,只是无意中在网上看到一篇文章,挺有意思。

下面的代码输出是几?答案是:2  而不是 3

class Test {
    public int aaa() {
        int x = 1;

        try {
            return ++x;
        } catch (Exception e) {

        } finally {
            ++x;
        }
        return x;
    }

    public static void main(String[] args) {
        Test t = new Test();
        int y = t.aaa();
        System.out.println(y);
    }
}

具体分析可以看下这篇文章        你真的了解try{ return }finally{}中的return?

原文地址:https://www.cnblogs.com/tinker/p/5766797.html