Popular posts from this blog
Rearrange Array in Maximum-Minimum form
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Naive Solution: Here we will use an auxiliary array to store the elements in correct order. For even indices of the array Large numbers from the given array are added. For odd indices small numbers are added. Code: import java.util.*; public class Test{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] a = {1,2,3,4,5,6,7,8,9}; int n = a.length; int[] temp = new int[n]; int small = 0; int large = n-1; for(int i=0; i<n; i++){ if(i%2 == 0){ temp[i] = a[large--]; } ...
Set Kth bit given number
Input : n = 10, k = 2 Output : 14 (10) 10 = (1010) 2 Now, set the 2nd bit from right. (14) 10 = (1 1 10) 2 2nd bit has been set. Input : n = 15, k = 3 Output : 15 3rd bit of 15 is already set. Code: import java.util.*; public class Solution { public static void main(String[] args){ int n = 10, k=2; //n = n | ( 1 << k ); n |= ( 1 << k ); System.out.print(n); } } Output: 14
Comments
Post a Comment