Codility – Lesson 5 Prefix Sums – CountDiv
プログラミング能力を評価するオンラインテスト、Codilityで、Lesson 5 Prefix Sums – CountDivに回答しました。
問題と結果画面
50%の評価。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; class Solution { public int solution(int A, int B, int K) { if(A < 0 || 2000000000 < A || B < 0 || 2000000000 < B || K < 1 || 2000000000 < K || B < A) throw new InvalidOperationException(); int cnt = 0; for(int i = A; i <= B; i++) { if(i % K == 0) cnt++; } return cnt; } } |
問題と結果画面
62%の評価。
Kの値が1の時の処理を追加。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; class Solution { public int solution(int A, int B, int K) { if(A < 0 || 2000000000 < A || B < 0 || 2000000000 < B || K < 1 || 2000000000 < K || B < A) throw new InvalidOperationException(); if(K == 1) return (B + 1) - A; int cnt = 0; for(int i = A; i <= B; i++) { if(i % K == 0) cnt++; } return cnt; } } |
問題と結果画面
75%の評価。
for文からwhile文に書き換え。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; class Solution { public int solution(int A, int B, int K) { if(A < 0 || 2000000000 < A || B < 0 || 2000000000 < B || K < 1 || 2000000000 < K || B < A) throw new InvalidOperationException(); int cnt = 0; int result = 0; while(cnt <= B) { if(A <= cnt) result++; cnt += K; } return result; } } |
問題と結果画面
87%の評価。
while内でcntの値がint型の最大値2147483647を上回る現象が発生。
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, int B, int K) { if(A < 0 || 2000000000 < A || B < 0 || 2000000000 < B || K < 1 || 2000000000 < K || B < A) throw new InvalidOperationException(); if(K == 1) return (B + 1) - A; int cnt = 0; int result = 0; while(cnt <= B) { if(A <= cnt) result++; cnt += K; } return result; } } |
問題と結果画面
100%の評価。
cntの値がint型の最大値を上回った時の予防策を追加。
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 |
using System; class Solution { public int solution(int A, int B, int K) { if(A < 0 || 2000000000 < A || B < 0 || 2000000000 < B || K < 1 || 2000000000 < K || B < A) throw new InvalidOperationException(); if(K == 1) return (B + 1) - A; int result = 0; int cnt = 0; while(cnt <= B) { if(cnt < 0) break; if(A <= cnt) result++; // Console.WriteLine("result : " + result); cnt += K; // Console.WriteLine("cnt : " + cnt); } return result; } } |