乘以七
我被问到这个面试问题: 一个数乘以 7 最快的方法是什么? 她告诉我不要使用任何 + 、 - 、 * 、 / 运算符。 紧张中,我无法回答这个问题。
我知道将数字乘以 8 的最快方法是 n<<3
但是n*7
能实现吗?
I was asked this interview question:
what is the quickest way to multiply a number by 7.
she told me not to use any of the + , - , * , /
operators.
In tense,i could not answer the question.
I know the quickest way to multiply a number by 8 is n<<3
but can n*7
be acheived?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
假设你的编译器并不糟糕,
n*7
。Assuming your compiler isn't terrible,
n*7
.几乎满足您的所有要求:)
Meets almost all your requirements :)
未使用禁止的运算符(
+
、-
、*
或/
):)No forbidden operators (
+
,-
,*
, or/
) used :)不确定这是否会比正常乘以 7 更好
Not sure if that will be better then normal multiplication by 7 though
正确的答案是 的组合,
因为这正是编译器完全能够自行计算出的微优化类型。
或者,如果面试官不是一无所知,则与上述 a) 不同的答案表明面试者不了解优化编译器,因此不适合该职位。 :-/
The correct answer is a combination of
because this is exactly the kind of micro-optimization that the compiler is perfectly capable of figuring out on its own.
Alternatively, if the interviewer isn't clueless, an answer different than a) above suggests that the interviewee does not understand optimizing compilers and is thus a poor candidate for the job. :-/
我能想到的最好答案是使用 while 循环和每个位的按位运算符编写“+”操作。像这样:
然后对 n 求和,n << 1、n<< 2.
“+”很容易用 while 循环编写,如果您能想出用 while 循环编写“-”的方法(我不知道到底如何做),那么您可以做到(n << 3 ) - n.
来源:http://geeki.wordpress.com/2007/12/12/adding-two-numbers-with-bitwise-and-shift-operators/
The best answer I can come up with is to write "+" operation using while loop and bitwise operators per each bit. Something like this:
And then sum up n, n << 1, n << 2.
"+" is easy to write with while loop, if you can come up with way to write "-" with while loop (which i am not sure how to do exactly) than you can do (n << 3) - n.
source:http://geeki.wordpress.com/2007/12/12/adding-two-numbers-with-bitwise-and-shift-operators/
很可能是
或者
It's likely either
or
也许这也是一个有效的答案:
pow(10, log10(n) + log10(7))
Maybe this is a valid answer as well :
pow(10, log10(n) + log10(7))
哦,你是如此接近!
= (n << 3 - n)
= n * 8 - n
= n(8 - 1)
= n * 7
oh you were so close!
= (n << 3 - n)
= n * 8 - n
= n(8 - 1)
= n * 7
假设面试官正在寻找一种移位和添加的答案,我想你可以使用:
我想这是一种测试面试者是否知道这个特定算法的粗略方法。
Assuming that the interviewer is looking for a shift-and-add kinda answer, I guess you could use:
I guess this a crude way of testing if the interviewee knows of this particular algo.
编辑:转换为c(我认为)并意识到c中没有.=,所以不得不切换到+=。从技术上讲仍然与 + 不同,但有点值得怀疑。
我知道它使用 ++ 但肯定与“+”不同,并且 .= 避免了规定。
EDIT: converted to c (i think) and realized there is no .= in c so had to switch to +=. Still not the same as + technically but a bit questionable.
I know it uses the ++ but that certainly not the same as "+" and .= avoids the stipulation.