Assumption: a < b
Note: If two or more numbers in the range have the same exponents of 2 , return the small number.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static int maxExponent(int a, int b){ int max = 0 for(int i=a; i<=b; i++){ if(count2s(i)>count2s(max)) max = i } return max; } public static int count2s(int num){ int count = 0; while(num!=0 && num%2==0){ count ++; num /= 2; } return count; } |
Python
def count2s(num): count = 0 while num%2==0 and num!=0: count += 1 num = num//2 return count def maxExponent(a, b): max = 0 for i in range(a,b+1): if(count2s(i)>count2s(max)): max = i return max |