Number of times all the numbers in an array are divisible by 2

情到浓时终转凉″ 提交于 2021-02-09 11:49:28

问题


I am trying to get the count of number of times all the integers in an array is divisible by 2 considering only one integer in each step. For example, initially if I have the array : [2,4,2] and count = 0

Step 1

[1,4,2] , count=1

Step 2

[1,2,2] , count=2

Step 3

[1,1,2] , count=3

Step 4

[1,1,1] , count=4

My approach to the problem is given below :

Code

public static void main(String[] args) {
     int[] ar={2,4,2};
     int[] p=new int[ar.length];
     int count=0;
     for (int i=0;i<ar.length ;i++ ) {
        if(ar[i]>=1){
            ar[i]=ar[i]/2;
            count++;
        }
     }
     for (int x:ar) {
        System.out.println(x);
     }
     System.out.println("Count:"+count);

}

Output

1
2
1
Count:3

The problem in the code given above is that the array is scanned only one time and I want to scan the array until all the integers are no more divisible by 2


回答1:


Note that you have two issues:

  1. You divide each element of the array by 2 at most one time.
  2. You divide elements of the array by 2 without checking first whether or not they are divisible by 2.

You need an inner loop that would divide each array element as long as it is divisible by 2:

public static void main(String[] args) {
     int[] ar={2,4,2};
     int[] p=new int[ar.length];
     int count=0;
     for (int i=0;i<ar.length ;i++ ) {
        while (ar[i] % 2 == 0 && ar[i] > 0) { // keep dividing ar[i] by 2 as long as 
                                              // it is divisible by 2
            ar[i]=ar[i]/2;
            count++;
        }
     }
     for (int x:ar) {
        System.out.println(x);
     }
     System.out.println("Count:"+count);
}



回答2:


     for (int i=0;i<ar.length ;i++ ) {
        while(ar[i]%2==0 && ar[i]>1){
            ar[i]=ar[i]/2;
            count++;
        }
     }

This will suffice.



来源:https://stackoverflow.com/questions/46386955/number-of-times-all-the-numbers-in-an-array-are-divisible-by-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!