更高效的版本?

时间:2010-12-29 09:47:35

标签: algorithm

我在这里有这个东西:

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;
}

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

1 个答案:

答案 0 :(得分:4)

我猜你用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;
}