[Quora] What is the most elegant line of code you've seen?

@Murtaza Aliakbar:

// Counting # bits set in 'v', Brian Kernighan's way
for (c = 0; v; c++)    v &= v - 1;
@Joshua Seims:

Euclid's Greatest Common Divisor algorithm (considered the oldest historical algorithm):

function (a, b) { return b ? gcb(b, a % b) : a; }
@Pradeep George Mathias:

Binary Search (The main "elegant" point is in line 3.)

int lo = 0, hi = N;
for (int mid = (lo + hi) / 2; hi - lo > 1; mid = (lo + hi) / 2)
    (arr[mid] > x ? hi : lo) = mid;
return lo;
// assuming N < 2^30, else "(lo + hi)" may overflow int
// can be worked around using lo + ( hi - lo) / 2

@Ravi Tandon:

Checking whether a (natural number > 1) is a power of two or not

return (!(x & (x - 1)));

@Vinay Bajaj

Swaps A and B:

A = A + B - (B = A);
@Jesse Tov:

while (*s++ = *t++);
(揸枪注:这是复制字符串的代码,在《C程序设计语言》那本书里。)
@Sugavanesh Balasubramanian:

Not exactly a line of code, but this is a terminal command 

(*Disclaimer: Don't ever try this command! - Reference: :(){ :|:& };:)

:(){ :|:& };:
@Chetan bademi:

Inverse square roots are used to compute angles of incidence and reflection for lighting and shading in computer graphics. This code uses integer operations, avoiding computationally expensive floating point operations, which makes it four times faster than normal floating point division. 

float FastInvSqrt(float x) {
    float xhalf = 0.5f * x;
    int i = *(int*) &x;                 // evil floating point bit level hacking
    i = 0x5f3759df - (i >> 1);          // what the fuck?
    x = *(float*) &i;
    x = x * (1.5f - (xhalf * x * x));
    return x;
}
@Thomas Le Feuvre:

One line sudoku solver(python)

def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]from sys import*;r(argv[1])
This is a  recursive algorithm for solving a sudoku. I don't think it's incredibly efficient though. It's a fun  one to work out what it's doing. If you are wanting to see a deep explanation of it see here:http://stackoverflow.com/questions/201461/shortest-sudoku-solver-in-python-how-does-it-work

@Brien Colwell:

For a 64-bit integer x,

for m in [0xff51afd7ed558ccdL, 0xc4ceb9fe1a85ec53L, 1]: x = (x ^ (x >>> 33)) * m
Applies t h e M urmurHash3 b it avalan che to generate a near-uniform distribution for x drawn from nearly any input distribution. Useful for uniformly distributing processing and data, much more efficient than md5 and other deep hashes.

@Jiten Thakkar:

while(x-->0) { /* Do something */ }
This gives a feeling of x tends to 0.

暂时就摘录这么多吧。这些都是我相对能看懂的语言写的代码,原文里还有perl和Haskell写的代码,因为我不懂,所以就没有贴出来了。对整个问题的答案有兴趣的朋友可以访问这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值