sexta-feira, 5 de agosto de 2022

Codility ParityDegree

I did this one by counting all the '0' at the right until we find the first 1.


For example 24 is 11000, we have 3 zeros this gives us the highest power of 2 that divides N.


For 28 we have 11100, we can only divide it by 2^2=4, for 10 we have 1010 we can only divide it by 2^1=2.
For 15 that is 1111, we cannot divide it by 2 but only by 2^0=1

// you can also use imports, for example: // import java.util.*; // you can write to stdout for debugging purposes, e.g. // System.out.println("this is a debug message"); class Solution { public int solution(int N) { // write your code in Java SE 8 String bin=Integer.toBinaryString(N); char binChar[]=bin.toCharArray(); int count=0; for (int i=bin.length()-1;i>=0 ;i--){ if (binChar[i]=='0') count++; else return count; } return count; } }

Sem comentários:

Enviar um comentário