BinaryGap
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of .N.
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of .N.
public int solution(int N) {
String binaryNo = Integer.toBinaryString(N);
int firstIndex = binaryNo.lastIndexOf("1");
int currentGap = 0;
int biggestGap = 0;
for (int i = firstIndex; i >= 0; i--) {
if (getNthDegit(binaryNo, i) == 0) {
currentGap++;
} else {
if (biggestGap < currentGap) {
biggestGap = currentGap;
}
currentGap = 0;
}
}
return biggestGap;
}
public static int getNthDegit(String number, int position) {
String numberString = "" + number;
char c = numberString.charAt(position);
return Character.getNumericValue(c);
}
OddOccurrencesInArray
Find value that occurs in odd number of elements.
public int solution(int[] A) { int num = 0; int max = 0; for (int i = 0; i < A.length; i++) { if (max <= A[i]) { max = A[i]; } } int[] B = new int[max]; for (int i = 0; i < A.length; i++) { if (B[A[i] - 1] == 0) { B[A[i] - 1] = A[i]; } else { B[A[i] - 1] = 0; } } for (int i = 0; i < B.length; i++) { if (B[i] != 0) { num = B[i]; break; } } return num; }
CyclicRotation
Each element is shifted right by one index, and the last element of the array is also moved to the first place.
public int[] solution(int[] A, int K) { if (K > 0 && A.length > 0) { K = K % A.length; int[] B = new int[A.length]; for (int i = 0; i < A.length; i++) { if ((i + K) > (A.length - 1)) { B[i + K - A.length] = A[i]; } else { B[i + K] = A[i]; } } return B; } else { return A; } }
FrogJmp
Count minimal number of jumps from position X to Y.
public int solution(int X, int Y, int D) { if (X == Y) return 0; else if ((Y - X) % D == 0) return ((Y - X) / D); else return ((Y - X) / D) + 1; }
Distinct
Compute number of distinct values in an array.
public int solution(int[] A) { Set<Integer> s = new HashSet<>(); for (int i = 0; i < A.length; i++) { s.add(A[i]); } return s.size(); }
CountDiv
Compute number of integers divisible by k in range [a..b].
public int solution(int A, int B, int K) {
return (B / K) - (A / K) + ((A % K) == 0 ? 1 : 0);
}
TapeEquilibrium
Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|. The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|.
public int solution(int[] A) {
int N = A.length;
int leftsum = 0;
int difference;
int rightSum;
int min = Integer.MAX_VALUE;
int sum = 0;
for (int i = 0; i < N; i++) {
sum = sum + A[i];
}
for (int i = 0; i < N - 1; i++) {
leftsum = leftsum + A[i];
rightSum = sum - leftsum;
difference = Math.abs(rightSum - leftsum);
min = Math.min(min, difference);
}
return min;
}
No comments:
Post a Comment