Skip to content

Instantly share code, notes, and snippets.

@Sharabaddin
Created February 23, 2018 17:49
Show Gist options
  • Save Sharabaddin/d19e44cb644e49f79383917fcd370e20 to your computer and use it in GitHub Desktop.
Save Sharabaddin/d19e44cb644e49f79383917fcd370e20 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 i = 0;
int j = array.length - 1;
for (i = 0; i < array.length / 2; i++, j--) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment