How to calculate the next multiple of 4 in C#

1 Answer

0 votes
using System;

class NextMmultipleOf4_CSharp
{
    static int NextMultipleOf4(int num)
    {
        return (num % 4 == 0) ? num + 4 : (num + 3) & ~0x03;
    }

    static void Main()
    {
        int[] nums = { 21, 16, 0, -9 };

        foreach (int num in nums) {
            Console.WriteLine(NextMultipleOf4(num));
        }
    }
}

  
  
  
/*
run:
  
24
20
4
-8
  
*/

 



answered Jul 27, 2024 by avibootz
edited Nov 21, 2024 by avibootz

Related questions

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