3 回答

TA貢獻2080條經驗 獲得超4個贊
public int getNextNumber(int[] array, int index) {
index = Math.floorMod(index, array.length) + 1;
return array[index];
}
我不懂 PHP,但我想這是準確的:
function getNextNumber(&$array, int $index) {
$index = fmod($index, count(array)) + 1
return $array[$index]

TA貢獻1796條經驗 獲得超4個贊
代碼
function getKey($current, $step): int
{
$keys = [1,2,3,4,5,6,7];
$currentKey = array_search($current, $keys);
$size = count($keys);
// normalize step offset
$step = ($step % $size) + $size;
// ^-----------^ ^-----^
// │ └ move possible negative to positive
// └ get a value from -7 to +7
// add offset for current key
$newKey = ($currentKey + $step) % $size;
// ^-----------------^ ^-----^
// │ └ wrap around in case we exceed $size
// └ add normalized step offset to new element to current
return $keys[$newKey];
}
// Tests
echo getKey(1,-1) . PHP_EOL;
echo getKey(3,1) . PHP_EOL;
echo getKey(7,1) . PHP_EOL;
echo getKey(7,15) . PHP_EOL; // same as +1
echo getKey(1,-8) . PHP_EOL; // same as -1
echo getKey(1,-15) . PHP_EOL; // same as -1
輸出
7
4
1
1
7
7
工作示例。

TA貢獻1825條經驗 獲得超6個贊
這個函數就可以解決問題,你應該使用 mod 來查找數字(對于 php 和 java 來說是“%”);
function myNextNumber($i){
if($i>6){
return ($i%7)+i;
}
return $i+1;
}
function myPreviousNumber($i){
if($i>8){
return $i%7-1;
}
if($i == 1){
return 7;
}
return $i-1;
}
function myNextNumber($i, $param){
if($param == 1){
return myNextNumber($i);
}
if($param == -1){
return myPreviousNumber($i);
}
return 'Invalit Param';
}
- 3 回答
- 0 關注
- 139 瀏覽
添加回答
舉報