I'm learning C#, I programmed some things in java, and I would like to have a feedback on my C# code.
The exercise is from codility
.
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Write a function:
class Solution { public int[] solution(int[] A, int K); }
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given
A = [3, 8, 9, 7, 6] K = 3 the function should return [9, 7, 6, 3, 8]. Three rotations were made: [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7] [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9] [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] For another example, given A = [0, 0, 0] K = 1 the function should return [0, 0, 0]
Given
A = [1, 2, 3, 4] K = 4 the function should return [1, 2, 3, 4]
And this is my code. It gives 100% but maybe something can be improved.Thanks in advice.
using System;
// you can also use other imports, for example:
// using System.Collections.Generic;
// you can write to stdout for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");
class Solution {
public int[] solution(int[] A, int K) {
int len = A.Length;
int[] B = new int[len];
if(len > 0 && K % len != 0 )
{
for ( int i = 0; i < len; i++)
{
B[(K + i) % len] = A[i];
}
}
else
{
return A;
}
return B;
}
}