分割正负数,无需与0进行比较,使用Java。

huangapple go评论66阅读模式
英文:

Partition negative and positive without comparison with 0 using java

问题

import java.util.*;

public class Source {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       int arr[] = new int[n];
       for (int i = 0; i < n; i++) {
           arr[i] = sc.nextInt();
       }
       partitionNegativeAndPositive(n, arr);
    }
    
    static boolean oppositeSign(int x, int y) {
        return ((x ^ y) < 0);
    }
    
    static void printList(ArrayList<Integer> list) {
        String result = "";
        for(int i = 0; i < list.size(); i++) {
            result += list.get(i) + " ";
        }
        System.out.println(result);
    }

    // Method to partition negative and positive numbers without comparing with 0
    static void partitionNegativeAndPositive(int n, int arr[]) {
        
        ArrayList<Integer> positiveNumbers = new ArrayList<Integer>();
        ArrayList<Integer> negativeNumbers = new ArrayList<Integer>();
        
        // Push the first element
        positiveNumbers.add(arr[0]);
        
        // Separate positive and negative numbers
        for (int i = 1; i < n; i++) {
            if (oppositeSign(positiveNumbers.get(0), arr[i])) {
                negativeNumbers.add(arr[i]);
            } else {
                positiveNumbers.add(arr[i]);
            }
        }
        
        // Print the results based on the sign of the first element
        if (arr[0] >= 0) {
            if (positiveNumbers.size() > 0) {
                printList(positiveNumbers);
            } else {
                System.out.println("Array doesn't have positive numbers");
            }
            if (negativeNumbers.size() > 0) {
                printList(negativeNumbers);
            } else {
                System.out.println("Array doesn't have negative numbers");
            }
        } else {
            if (negativeNumbers.size() > 0) {
                printList(negativeNumbers);
            } else {
                System.out.println("Array doesn't have negative numbers");
            }
            if (positiveNumbers.size() > 0) {
                printList(positiveNumbers);
            } else {
                System.out.println("Array doesn't have positive numbers");
            }
        }
    }
}
英文:

You will be given an array of n integers, both negative and positive. You need to partition the array into positive and negative numbers. Add all the positive integers of the array to one array (or any data structure) and add all the negative to another array (or any data structure). If the first element of the input array is a positive number, then print all the positive numbers in the given order in the first line of output, and then all the negative numbers in the given order in the second line of output, vice - versa.

Notes:

Consider 0 as a positive number.

The positive and negative numbers in the output should follow the order of the elements in the given array. Each number in each line of the output should be separated by a space.

If the array contains only positive numbers then print the positive numbers in the first line and in the second line print “Array doesn't have negative numbers”.

If the array contains only negative numbers then print the negative numbers in the first line and in the second line print “Array doesn't have positive numbers”.

Input:

10

2 6 9 -1 -4 10 -7 3 5 -8

Output:

2 6 9 10 3 5

-1 -4 -7 -8

Explanation:

The first element of the array is 2 that is a positive number so print all the positive numbers of the array in the first line and then print all the negative numbers in the next line

Here what I have done which is working 50%(which is partitioning -ve and +ve integers in separate arraylist) and that remaining 50% where we have to check whether in our array if no positive numbers given then print the given message and vice versa

 import java.util.*;
public class Source {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i &lt; n; i++) {
arr[i] = sc.nextInt();
}
partitionNegativeAndPositive(n, arr);
}
static  boolean oppositeSign(int x,int y) {
return ((x^y)&lt;0);
}
static void printList(ArrayList&lt;Integer&gt; list) {
String result=&quot;&quot;;
for(int i=0;i&lt;list.size();i++) {
result+=list.get(i)+&quot; &quot;;
}
System.out.println(result);
}
// Method to partition negative and positive numbers without comparing with 0
static void partitionNegativeAndPositive(int n, int arr[]) {
// Write your code here
ArrayList&lt;Integer&gt; a = new ArrayList&lt;Integer&gt;();
ArrayList&lt;Integer&gt; b = new ArrayList&lt;Integer&gt;();
//push first element
a.add(arr[0]);
// Now put all elements of same sign
// in a[] and opposite sign in b[]
for(int i=1;i&lt;n;i++) {
if(oppositeSign( a.get(0), arr[i])) {
b.add(arr[i]);
}else {
a.add(arr[i]);
}
}
if(arr[0]&gt;=0) {
if(a.size()&gt;=0) {
printList(a);
}else {
System.out.println(&quot;Array doesn&#39;t have positive numbers&quot;);
}
if(b.size()&gt;=0) {
printList(b);
}else {
System.out.println(&quot;Array doesn&#39;t have negative numbers&quot;);
}
}else {
if(b.size()&gt;=0) {
printList(b);
}else {
System.out.println(&quot;Array doesn&#39;t have negative numbers&quot;);
}
if(a.size()&gt;=0) {
printList(a);
}else {
System.out.println(&quot;Array doesn&#39;t have positive numbers&quot;);
}
}
}
}

Please help where I have done wrong in this piece of code

答案1

得分: 7

你的oppositeSign方法是一个不错的想法,但它仍然与零进行了比较。当你考虑到int值的最左位表示符号并且可以被提取出来用作索引来分割时,你可以在不进行比较的情况下执行分割操作。此外,Java不是C语言。你不需要传递数组长度,因为Java数组知道它们的长度。另外,你应该避免使用声明语法int arr[],而是使用int[] arr,以遵循符合惯例的“类型名称”模式。

static void partitionNegativeAndPositive(int[] arr) {
    ArrayList<Integer> pos = new ArrayList<>(), neg = new ArrayList<>();

    List<List<Integer>> posNeg = Arrays.asList(pos, neg);

    for (int i : arr) {
        posNeg.get(i >>> 31).add(i);
    }

    if (pos.isEmpty()) {
        System.out.println("数组中没有正数");
    } else {
        printList(pos);
    }
    if (neg.isEmpty()) {
        System.out.println("数组中没有负数");
    } else {
        printList(neg);
    }
}

i >>> 31 将符号位移动到位置零,对于正数得到零,对于负数得到一。这可以用作索引,通过Arrays.asList(pos, neg)创建的列表中添加到正确的分区。

英文:

Your oppositeSign method is a nice idea, but it still bears a comparison with zero. You can perform the partition operation without comparisons when you consider that the leftmost bit of an int value indicates the sign and can be extracted, to be used as an index into your partitions. Further, Java is not C. You don’t need to pass the array length, as Java arrays know their length. Further, you should avoid the declaration syntax int arr[], but use int[] arr, to follow the idiomatic type name pattern.

static void partitionNegativeAndPositive(int[] arr) {
ArrayList&lt;Integer&gt; pos = new ArrayList&lt;&gt;(), neg = new ArrayList&lt;&gt;();
List&lt;List&lt;Integer&gt;&gt; posNeg = Arrays.asList(pos, neg);
for(int i: arr) posNeg.get(i &gt;&gt;&gt; 31).add(i);
if(pos.isEmpty()) {
System.out.println(&quot;Array doesn&#39;t have positive numbers&quot;);
}
else {
printList(pos);
}
if(neg.isEmpty()) {
System.out.println(&quot;Array doesn&#39;t have negative numbers&quot;);
}
else {
printList(neg);
}
}

i &gt;&gt;&gt; 31 shifts the sign bit to position zero, leading to zero for positive numbers and one for negative numbers. This can be used as index into the list created via Arrays.asList(pos, neg), to add to the correct partition.

答案2

得分: 1

代码中的问题是你正在检查数组的大小是否为零或更多,然后打印该数组,否则打印消息。但是数组的大小始终只能是零或更多。

为了获得所需的输出,您只需要进行以下更改。

if (arr[0] >= 0) {
    if (a.size() > 0) { // < -- 仅比较大小是否大于零
        printList(a);
    } else {
        System.out.println("数组中没有正数");
    }
    if (b.size() > 0) { // < -- 仅比较大小是否大于零
        printList(b);
    } else {
        System.out.println("数组中没有负数");
    }
} else {
    if (b.size() > 0) { // < -- 仅比较大小是否大于零
        printList(b);
    } else {
        System.out.println("数组中没有负数");
    }
    if (a.size() > 0) { // < -- 仅比较大小是否大于零
        printList(a);
    } else {
        System.out.println("数组中没有正数");
    }
}
英文:

The issue in the code is you are checking for the size of the array to be zero or more then print that array else print the message.
But the size of array will always be either zero or more.

To get the desired output ,you just have to make the below changes.

     if(arr[0]&gt;=0) {
if(a.size()&gt;0) { // &lt;--  compare for size greater than 0 only
printList(a);
}else {
System.out.println(&quot;Array doesn&#39;t have positive numbers&quot;);
}
if(b.size()&gt;0) { // &lt;--  compare for size greater than 0 only
printList(b);
}else {
System.out.println(&quot;Array doesn&#39;t have negative numbers&quot;);
}
}else {
if(b.size()&gt;0) { // &lt;--  compare for size greater than 0 only
printList(b);
}else {
System.out.println(&quot;Array doesn&#39;t have negative numbers&quot;);
}
if(a.size()&gt;0) { // &lt;--  compare for size greater than 0 only
printList(a);
}else {
System.out.println(&quot;Array doesn&#39;t have positive numbers&quot;);
}
}

答案3

得分: 0

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
		int arr[] = {-2, -6, -9, -1, -4, -10, -7, -3, -5, -8};

		boolean isPositive = false;
		boolean isNegative = false;

		boolean fElement = arr[0] >= 0;

		ArrayList<Integer> pos = new ArrayList<Integer>();
		ArrayList<Integer> neg = new ArrayList<Integer>();

		for(int i : arr){
			if(i >= 0){
				pos.add(i);
				isPositive = true;
			}else{
				neg.add(i);
				isNegative = true;
			}
		}

		if(fElement){
			for(int i : pos){
				System.out.print(i + " ");
			}
			System.out.println();

			if(isNegative){
				for(int i : neg){
					System.out.print(i + " ");
				}
			}else{
				System.out.println("No negative numbers");
			}

		}else{
			for(int i : neg){
				System.out.print(i + " ");
			}
			System.out.println();

			if(isPositive){
				for(int i : pos){
					System.out.print(i + " ");
				}
			}else{
				System.out.println("No positive numbers");
			}

		}
    }
}
英文:
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
		int arr[] = {-2, -6, -9, -1, -4, -10, -7, -3, -5, -8};

		boolean isPositive = false;
		boolean isNegative = false;

		boolean fElement = arr[0] &gt;= 0;

		ArrayList&lt;Integer&gt; pos = new ArrayList&lt;Integer&gt;();
		ArrayList&lt;Integer&gt; neg = new ArrayList&lt;Integer&gt;();

		for(int i : arr){
			if(i &gt;= 0){
				pos.add(i);
				isPositive = true;
			}else{
				neg.add(i);
				isNegative = true;
			}
		}

		if(fElement){
			for(int i : pos){
				System.out.print(i + &quot; &quot;);
			}
			System.out.println();

			if(isNegative){
				for(int i : neg){
					System.out.print(i + &quot; &quot;);
				}
			}else{
				System.out.println(&quot;No negative numbers&quot;);
			}

		}else{
			for(int i : neg){
				System.out.print(i + &quot; &quot;);
			}
			System.out.println();

			if(isPositive){
				for(int i : pos){
					System.out.print(i + &quot; &quot;);
				}
			}else{
				System.out.println(&quot;No positvie numbers&quot;);
			}

		}
    }
}

答案4

得分: 0

import java.util.*;

public class array_partition {

   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       int arr[] = new int[n];
       for (int i = 0; i < n; i++) {
           arr[i] = sc.nextInt();
       }
       partitionNegativeAndPositive(n, arr);
   }

   static  boolean oppositeSign(int x, int y) {
       return ((x^y)<0);
   }

   // Method to partition negative and positive numbers without comparing with 0
   static void partitionNegativeAndPositive(int n, int arr[]) {
      // Write your code here
     
     ArrayList<Integer> a = new ArrayList<Integer>();
     ArrayList<Integer> b = new ArrayList<Integer>();
     
     a.add(arr[0]);
     // Now put all elements of the same sign
     // in a[] and the opposite sign in b[]
     for(int i = 1; i < n; i++) {
         if (oppositeSign(a.get(0), arr[i])) {
             b.add(arr[i]);
         } else {
             a.add(arr[i]);
         }
     }
     
     if (a.size() == n && a.get(0) >= 0) {
         print_arraylist(a);
         System.out.println();
         System.out.println("Array doesn't have negative numbers");
     } else if (a.size() == n && a.get(0) < 0) {
         print_arraylist(a);
         System.out.println();
         System.out.println("Array doesn't have positive numbers");
     } else {
         print_arraylist(a);
         System.out.println();
         print_arraylist(b);
     }
   }
   
   static void print_arraylist(ArrayList<Integer> list) {
       for (int i : list) {
           System.out.print(i + " ");
       }
   }
}
英文:
import java.util.*;
public class array_partition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i &lt; n; i++) {
arr[i] = sc.nextInt();
}
partitionNegativeAndPositive(n, arr);
}
static  boolean oppositeSign(int x,int y) {
return ((x^y)&lt;0);
}
// Method to partition negative and positive numbers without comparing with 0
static void partitionNegativeAndPositive(int n, int arr[]) {
// Write your code here
ArrayList&lt;Integer&gt; a=new ArrayList&lt;Integer&gt;();
ArrayList&lt;Integer&gt; b=new ArrayList&lt;Integer&gt;();
a.add(arr[0]);
// Now put all elements of same sign
// in a[] and opposite sign in b[]
for(int i=1;i&lt;n;i++) {
if(oppositeSign( a.get(0), arr[i])) {
b.add(arr[i]);
}else {
a.add(arr[i]);
}
}
if(a.size()==n &amp;&amp; a.get(0)&gt;=0) {
print_arraylist(a);
System.out.println();
System.out.println(&quot;Array doesn&#39;t have negative numbers&quot;);
}
else if(a.size()==n &amp;&amp; a.get(0)&lt;0) {
print_arraylist(a);
System.out.println();
System.out.println(&quot;Array doesn&#39;t have positive numbers&quot;);
}
else {
print_arraylist(a);
System.out.println();
print_arraylist(b);
}
}
static void print_arraylist(ArrayList&lt;Integer&gt; list) {
for(int i:list) {
System.out.print(i+&quot; &quot;);
}
}
}

huangapple
  • 本文由 发表于 2020年8月26日 15:34:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63592681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定