How to calculate the next multiple of 4 in JavaScript

2 Answers

0 votes
function next_multiple_of_4(num) { 
    return (num % 4 === 0) ? num + 4 : (num + 3) & ~0x03; 
} 

let nums = [21, 16, 0, -9]; 

nums.forEach(num => { 
    console.log(next_multiple_of_4(num)); 
});


 
/*
run:
 
24
20
4
-8

*/

 



answered Nov 21, 2024 by avibootz
edited Nov 21, 2024 by avibootz
0 votes
function next_multiple_of_4(num) { 
    return num + (4 - num % 4)
} 

let nums = [21, 16, 0, -9]; 

nums.forEach(num => { 
    console.log(next_multiple_of_4(num)); 
});


 
/*
run:
 
24
20
4
-4

*/

 



answered Nov 21, 2024 by avibootz

Related questions

1 answer 80 views
2 answers 105 views
1 answer 114 views
1 answer 125 views
2 answers 175 views
1 answer 104 views
1 answer 105 views
...