Leetcode / Leetcode (2)
.odt66. Plus One
public class Solution
{
public int[] PlusOne(int[] digits)
{
for (int i = digits.Length - 1; i >= 0; i--)
{
if (digits[i] != 9)
{
digits[i]++;
return digits;
}
digits[i] = 0;
}
digits = new int[digits.Length + 1];
digits[0] = 1;
return digits;
}
}
69. Sqrt(x)
public class Solution
{
public int MySqrt(int x)
{
if (x == 1)
{
return x;
}
for (double i = 0; i <= x; i++)
{
if (i * i > x)
{
return Convert.ToInt32(i - 1);
break;
}
}
return 0;
}
}
191. Number of 1 Bits
public class Solution
{
public int HammingWeight(int n)
{
int count = 0;
while (n != 0)
{
if ((n & 1) == 1)
{
count++;
}
n >>>= 1;
}
return count;
}
}
231. Power of Two
public class Solution
{
public bool IsPowerOfTwo(int n)
{
if (n < 1)
return false;
while (n >= 2)
{
if ((n % 2 != 0 && n != 1))
return false;
n = n / 2;
}
return true;
}
}
190. Reverse Bits
public class Solution
{
public uint reverseBits(uint n)
{
uint result = 0;
for (int i = 0; i < 32; i++)
{
result <<= 1;
result |= (n & 1);
n >>= 1;
}
return result;
}
}
20. Valid Parentheses
public class Solution
{
public bool IsValid(string s)
{
while (s.Contains("()") || s.Contains("[]") || s.Contains("{}"))
{
s = s.Replace("()", "").Replace("[]", "").Replace("{}", "");
}
return s.Length == 0;
}
}
