我这儿有件事:

function numOfPackets(bufferSize, packetSize) {
    if (bufferSize <= 0 || packetSize > bufferSize) return 0;
    if (packetSize < 0) throw Error();
    var out = 0;


    for(;;){
     out++;
     bufferSize = bufferSize - packetSize;
     if( packetSize > bufferSize ) break;
    }

    return out;
}

我经常跑,你能给我更有效的变种吗?

最佳答案

我猜您是用javascript或类似的语言编写的,在这种情况下使用:

function numOfPackets(bufferSize, packetSize) {
    if (bufferSize <= 0) return 0;
    if (packetSize <= 0) throw Error();
    return Math.floor(bufferSize / packetSize);
}

还要注意,当packetSize = 0时,原始代码进入无限循环;
等价于C++:
int numOfPackets(int bufferSize, int packetSize) {
    if (bufferSize <= 0) return 0;
    if (packetSize <= 0) throw Error();
    return bufferSize / packetSize;
}

关于algorithm - 更有效的版本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4553028/

10-11 01:52