I come across in Codility problem where if i used A == null a run time error still encounters. Problem: An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place.
where the error encountered: input ([],1) The question is does null doesn't validate the value of A?
class Solution {
public int[] solution(int[] A, int K) {
if(A == null){
return A;
}
for(int y = 0; y < K; y++){
int temp = A[A.length - 1];
for(int x = A.length - 1; x > 0; x --){
A[x] = A[x - 1];
}
A[0] = temp;
}
return A;
}
So instead of using if I tried to use Try catch and it worked.
class Solution {
public int[] solution(int[] A, int K) {
try{
for(int y = 0; y < K; y++){
int temp = A[A.length - 1];
for(int x = A.length - 1; x > 0; x --){
A[x] = A[x - 1];
}
A[0] = temp;
}
return A;
}
catch(ArrayIndexOutOfBoundsException e){
return A;
}
}
}