my_leetcode/c_sharp/my_leetcode/Solution.cs

63 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace my_leetcode
{
internal class Solution
{
/// <summary>
/// 268.丢失的数字
/// </summary>
/// <param name="nums">数组</param>
/// <returns>丢失的数字</returns>
public int MissingNumber(int[] nums)
{
return new int[4] { nums.Length, 1, nums.Length + 1, 0 }[nums.Length & 3] ^ nums.Aggregate(0, (o, n) => o ^ n);
}
/// <summary>
/// 69.Sqrt(x)
/// </summary>
/// <param name="x">x</param>
/// <returns>平方根</returns>
public int MySqrt(int x)
{
double xHalf = 0.5 * x;
long i = BitConverter.DoubleToInt64Bits(x);
i = 0x1FF7A3BEA91D9B1B + (i >> 1);
double f = BitConverter.Int64BitsToDouble(i);
f = f * 0.5 + xHalf / f;
f = f * 0.5 + xHalf / f;
f = f * 0.5 + xHalf / f;
return (int)f;
}
/// <summary>
/// 640. 求解方程
/// </summary>
/// <param name="equation">方程式</param>
/// <returns>解</returns>
public string SolveEquation(string equation)
{
var (a, b, c, sign, left, hasC) = (0, 0, 0, 1, 1, false);
foreach (var z in equation)
{
(a, b, c, sign, left, hasC) = z switch
{
'x' => (a + (hasC ? sign * left * c : sign * left), b, 0, sign, left, false),
'+' => (a, b + sign * left * c, 0, 1, left, false),
'-' => (a, b + sign * left * c, 0, -1, left, false),
'=' => (a, b + sign * left * c, 0, 1, -1, false),
_ => (a, b, c * 10 + z - '0', sign, left, true)
};
}
b += sign * left * c;
return a == 0 ? b == 0 ? "Infinite solutions" : "No solution" : "x=" + -b / a;
}
}
}