feat(makeTheIntegerZeio): add C# solution
This commit is contained in:
@@ -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();
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
Reference in New Issue
Block a user