diff --git a/problems/2749-minimum-operations-to-make-the-integer-zero/csharp/Program.cs b/problems/2749-minimum-operations-to-make-the-integer-zero/csharp/Program.cs new file mode 100644 index 0000000..7a81016 --- /dev/null +++ b/problems/2749-minimum-operations-to-make-the-integer-zero/csharp/Program.cs @@ -0,0 +1,84 @@ +// LeetCode 2749: Minimum Operations To Make The Integer Zero +// 難度: Medium +// 日期: 2025-09-05 + +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution +{ + public int MakeTheIntegerZero(int num1, int num2) + { + for (int k = 1; k <= 60; k++) + { + long target = (long)num1 - (long)k * num2; + + if (target < 0) continue; + + int bitCount = CountSetBits(target); + + if (bitCount <= k && k <= target) + { + return k; + } + } + + return -1; + } + + private int CountSetBits(long n) + { + int count = 0; + while (n > 0) + { + // 方法一 + // count += (int)(n & 1); + // n >>= 1; + + // 方法二 + count++; + n &= n - 1; + } + return count; + } +} + +public class Program +{ + public static void Main() + { + Solution solution = new Solution(); + TestCase1(solution); + TestCase2(solution); + } + + static void TestCase1(Solution solution) + { + int num1 = 3, num2 = -2; + int expected = 3; + int actual = solution.MakeTheIntegerZero(num1, num2); + + Console.WriteLine("Test 1:"); + Console.WriteLine($"Input: num1 = {num1}, num2 = {num2}"); + Console.WriteLine($"Expected: {expected}"); + Console.WriteLine($"Actual: {actual}"); + Console.WriteLine($"Result: {(actual == expected ? "PASS" : "FAIL")}"); + Console.WriteLine(); + } + + static void TestCase2(Solution solution) + { + int num1 = 5, num2 = 7; + int expected = -1; + int actual = solution.MakeTheIntegerZero(num1, num2); + + Console.WriteLine("Test 2:"); + Console.WriteLine($"Input: num1 = {num1}, num2 = {num2}"); + Console.WriteLine($"Expected: {expected}"); + Console.WriteLine($"Actual: {actual}"); + Console.WriteLine($"Result: {(actual == expected ? "PASS" : "FAIL")}"); + Console.WriteLine(); + } + +} diff --git a/problems/2749-minimum-operations-to-make-the-integer-zero/csharp/csharp.csproj b/problems/2749-minimum-operations-to-make-the-integer-zero/csharp/csharp.csproj new file mode 100644 index 0000000..2150e37 --- /dev/null +++ b/problems/2749-minimum-operations-to-make-the-integer-zero/csharp/csharp.csproj @@ -0,0 +1,10 @@ + + + + Exe + net8.0 + enable + enable + + +