印象深刻的笔试题:分解任意整数以质因子相乘的形式
刚毕业时,第一次参加招聘面试的笔试,一道编程题:分解一个整数以质因子相乘的形式,如24=2x2x2x3,100=2x2x5x5。(在纸上手写代码)
我的核心代码:Java Code
public static String resolve(int value) {
String str = "";
int temp = value;
for (int i = 2; i <= Math.sqrt(value);) {
if (temp % i == 0) {
temp /= i;
str += i + "x";
continue;
}
i++;
}
return str.substring(0, str.length() - 1);
}
记得当时面试官提了好多次疑问,这样真的可以实现吗?让我有点无语,我也给解释了半天,不过我走之前好像还是没想清楚,所以让我印象深刻。