构造N输入OR门。如果所有输入都为0,则OR门返回0,否则使用java

时间:2016-09-06 07:28:58

标签: java loops variables

确切的问题 http://www.practice.geeksforgeeks.org/problem-page.php?pid=1335

  

构造N输入OR门。如果所有输入都是OR门,则返回0   为0,否则为1。

  • 输入:

  • 3 //这些是测试用例

  • 2 //这些是输入数量

  • 1 1 //这些是输入

  • 3 //这些

  • 0 0 0

  • 4

  • 1 1 1 0

  •   

    输出:1 // o / p表示第一种情况

  • 0 // o / p for second case

  • 1

此代码导致运行时错误

  

错误,如Scanner java:907,java:1530,java:2160

    class GFG {

            static int or(int a[] , int n , int x){
               for(int i = 0;i<n;i++)
               {
                   if(x==0)
                      return 0;
               }
                 return 1;
        }
    public static void main (String[] args) {
        int a[] = new int[100];
        int x= 0;
        Scanner in  =new Scanner(System.in);
        int t = in.nextInt();
        while(t>0){
            int n = in.nextInt();
            for(int i =0; i<n;i++){
               a[i] = in.nextInt();
               x =x+(a[i]|a[i+1]);
            }
               System.out.println(or(a,n,x));
               t--;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你的代码大部分都适用,但是:

for(int i = 0; i < n; i++) {
    if(x == 0)
        return 0;
}
return 1;

相当于:

if(x == 0) return 0; else return 1;

你想要的是:

for(int i = 0; i < n; i++) {
    if(a[i] == 0)
        return 0;
}
return 1;

事实上,您可以完全取消x,但如果您想使用x,则无需将数字存储在a中。

没有数组的版本

public static void main (String[] args) {
    int x = 0; // assume x is 0.
    Scanner in  = new Scanner(System.in);
    int t = in.nextInt();
    while(t > 0) {
        int n = in.nextInt();
        x = 0; // reinitialise x each time.
        for(int i = 0; i < n; i++) {
            // if and only if all inputs are 0 will x be 0.
            // if any input is 1 -> x | 1 is 1 no matter what x. So the result will be 1.
            x = x | in.nextInt();
        }
        System.out.println(x);
        t--;
    }
    in.close();
}

输入对话框:

Location of input dialog box

您可以使用网站提供的示例输入。