プログラミング能力を評価するオンラインテスト、Codilityで、Lesson 2 Arrays – OddOccurrencesInArrayに回答しました。
問題と結果画面
66%の評価。
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
|
using System; class Solution { public int solution(int[] A) { bool isUnpaired; for (int i = 0; i < A.Length; i++) { if(A [i] == 0) continue; isUnpaired = true; for(int j = i + 1; j < A.Length; j++) { if(A [i] == A [j]) { isUnpaired = false; A [j] = 0; break; } } if (isUnpaired) { return A [i]; } } return 0; } } |
問題と結果画面
100%の評価。
for文を2つから1つに。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
using System; class Solution { public int solution(int[] A) { System.Array.Sort(A); for (int i = 0; i < A.Length; i++) { if(A [i] < 1 || 1000000000 < A [i]) throw new System.InvalidOperationException(); if((i % 2) == 1) continue; if(A.Length <= i + 1) return A [i]; if(A [i] != A [i + 1]) return A [i]; } return 0; } } |
問題と結果画面
100%の評価。
XOR演算子を使えばこんなに簡潔にも書ける。
ビット演算っておもしろい。
|
using System; class Solution { public int solution(int[] A) { int unpairedInt = 0; foreach (int val in A) { unpairedInt ^= val; } return unpairedInt; } } |
プログラミング能力を評価するオンラインテスト、Codilityで、Lesson 2 Arrays – CyclicRotationに回答しました。
問題と結果画面
100%の評価。
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
|
using System; using System.Collections.Generic; class Solution { public int[] solution(int[] A, int K) { if (A.Length < 1) return A; List<int> list = new List<int> (); foreach(int a in A) { list.Add (a); } for (int i = 0; i < K; i++) { int last = list [list.Count - 1]; list.RemoveAt (list.Count - 1); list.Insert (0, last); } for (int i = 0; i < A.Length; i++) { A[i] = list[i]; } return A; } } |
プログラミング能力を評価するオンラインテスト、Codilityで、Lesson 1 Iterations – BinaryGapに回答しました。
問題と結果画面
100%の評価。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
using System; class Solution { public int solution(int N) { int length = 0; string binary = System.Convert.ToString(N, 2); string[] values = binary.Split ('1'); for(int i = 0; i < values.Length - 1; i++) { if(length < values [i].Length) { length = values [i].Length; } } return length; } } |
I love playing the piano. I’d like to practice more.
But, I cannot spare much time for it these days.

C# 5.0 in a Nutshell: The Definitive Reference by Definitive Reference Kindle Edition
by Joseph Albahari, Ben Albahari.
The ?? operator:
– can be used with both nullable types and reference types.
– says “If the operand is non-null, give it to me; otherwise, give me a default value.”
– equivalent to calling GetValueOrDefault with an explicit default value, except that the expression for the default value is never evaluated if the variable is not null.
|
int? x = null; int y = x ?? 5; // y is 5 |
|
int? a = null, b = 1, c = 2; Console.WriteLine(a ?? b ?? c); // 1 (first non-null value) |
Albahari & Albahari, C# 5.0 In a Nutshell: The Definitive Reference, 156-157.