Skip to content

Instantly share code, notes, and snippets.

@Sharabaddin
Created February 23, 2018 17:43
Show Gist options
  • Save Sharabaddin/876ad5bb07dfeab8176667350ba1da34 to your computer and use it in GitHub Desktop.
Save Sharabaddin/876ad5bb07dfeab8176667350ba1da34 to your computer and use it in GitHub Desktop.
import java.util.Arrays; //исключительно для быстрого вывода результата
public class HelloWorld{
public static void main(String []args){
// Call task 1
int testNumber = 100;
System.out.println("Task1 v1: " + checkBinaryOne(testNumber));
// Call task 1 v2 Optimized
System.out.println("Task1 v2: " + checkBinaryOneOptimizedVery(testNumber));
// Call task 1 v3 very Optimized
System.out.println("Task1 v3: " + checkBinaryOneOptimizedVery(testNumber));
// Call task 2
int[] testArray = {
1, 2, 3,
};
System.out.println("Task2: " + Arrays.toString(reverseArray(testArray)));
}
//task1
public static int checkBinaryOne(int number) {
int sum = 0;
String binaryText = Integer.toBinaryString(number);
System.out.println("debug bin:" + binaryText);
for (int i = 0; i < binaryText.length(); i++) {
if (binaryText.charAt(i) == '1') {
sum++;
}
}
return sum ;
}
//task1 v2
public static int checkBinaryOneOptimizedVery(int number) {
number = number - ((number >>> 1) & 0x55555555);
number = (number & 0x33333333) + ((number >>> 2) & 0x33333333);
return (((number + (number >>> 4)) & 0x0F0F0F0F) * 0x01010101) >>> 24;
}
//task1 v3
public static int checkBinaryOneOptimized(int number) {
int count;
for (count = 0; number > 0; ++count) {
number &= number - 1;
}
return count;
}
//task1
public static int[] reverseArray(int[] array) {
int[] resultArray = new int[array.length];
for(int i = 0; i < array.length; i++) {
resultArray[i] = array[array.length - 1 - i];
}
return resultArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment