dharamendra1314
BAN USERpublic static int multiply(int a,int b){
// flag to store if result is positive or negative
boolean isNegative = false;
// if both numbers are negative, make both numbers
// positive as result will be positive anyway
if (a < 0 && b < 0) {
a = -a;
b = -b;
}
// if only a is negative, make it positive
// and mark result as negative
if (a < 0) {
a = -a;
isNegative = true;
}
// if only b is negative, make it positive
// and mark result as negative
if (b < 0) {
b = -b;
isNegative = true;
}
int res =0;
// While second number doesn't become 1
while (b!=0){
// If second number becomes odd,
// add the first number to result
if((b&1)!=0){
res +=a;
}
// Double the first number
// and halve the second number
a = a <<1;
b = b >>1;
}
return (isNegative) ? -res : res;
}
public int[] getDistanceFromRoot(Node head,int[] arr){
int[] result = new int[arr.length];
Arrays.fill(result,-1);
Map<Integer,Integer> map = new HashMap<>();
for(int j =0; j<arr.length;j++){
map.putIfAbsent(arr[j],j);
}
Queue<Node> queue = new LinkedList<>();
queue.offer(head);
int level =0;
while (!queue.isEmpty()){
int size = queue.size();
while (size > 0){
Node temp = queue.poll();
if(map.containsKey(temp.val) && result[map.get(temp.val)]==-1){
result[map.get(temp.val)]= level;
}
if(temp.left !=null)
queue.add(temp.left);
if(temp.right !=null)
queue.add(temp.right);
size--;
}
level++;
}
return result;
}
- dharamendra1314 February 01, 2021