-
Notifications
You must be signed in to change notification settings - Fork 4
/
hello.ci
63 lines (58 loc) · 1.43 KB
/
hello.ci
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class HelloCi
{
public const int VersionMajor = 0;
public const int VersionMinor = 3;
public const string Version = VersionMajor + "." + VersionMinor;
/// Returns `true` if and only if `x` is a power of 2 (1, 2, 4, 8, 16, ...).
public static bool IsPowerOfTwo(int x)
{
return (x & x - 1) == 0 && x > 0;
}
/// Calculates greatest common divisor of `a` and `b`.
public static int GreatestCommonDivisor(int a, int b)
{
// Euclidean algorithm
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
/// Checks whether the given string is a palindrome.
/// Note: empty string is considered palindrome.
public static bool IsPalindrome(string s)
{
int j = s.Length;
for (int i = 0; i < --j; i++)
if (s[i] != s[j])
return false;
return true;
}
/// Gets a boolean value out of strings `"true"` and `"false"`.
/// In other cases returns `defaultValue`.
public static bool ParseBool(string s, bool defaultValue)
{
if (s == "true")
return true;
if (s == "false")
return false;
return defaultValue;
}
/// Converts an unsigned integer from its decimal representation.
public static int ParseUnsignedInt(string s)
{
if (s == null || s.Length == 0)
throw "null or empty argument";
int n = s.Length;
int r = 0;
for (int i = 0; i < n; i++) {
int c = s[i];
if (c < '0' || c > '9')
throw "Not a digit";
// TODO: detect overflow
r = r * 10 + c - '0';
}
return r;
}
}