数组中所有数字被2整除的次数 [英] Number of times all the numbers in an array are divisible by 2

查看:99
本文介绍了数组中所有数字被2整除的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取一个 array 中所有 integers 的被2除的次数,只考虑其中的一个 integer 每一步.例如,最初,如果我有 array : [2,4,2] count = 0

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

第1步

[1,4,2] , count=1

第2步

[1,2,2] , count=2

第3步

[1,1,2] , count=3

第4步

[1,1,1] , count=4

我的解决方法如下:

代码

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);

}

输出

1
2
1
Count:3

上面给出的代码中的问题是 array 仅被扫描了一次,而我想扫描该数组,直到所有 integers不能再被2整除

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

推荐答案

请注意,您有两个问题:

Note that you have two issues:

  1. 您最多一次将数组的每个元素除以2.
  2. 您可以将数组的元素除以2,而无需先检查它们是否可以被2整除.

您需要一个内部循环,该循环将分隔每个数组元素,只要它可以被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整除的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆