First, the topic requirements
Title: Returns the and of the largest sub-array in an integer array.
Requirements:
Requires that the procedure be capable of handling 1000 elements;
Each element is of the int32 type;
Enter an array of shapes with positive and negative numbers in the array.
One or more consecutive integers in an array make up a sub-array, each of which has a and.
The maximum value for the and of all sub-arrays. Requires a time complexity of O (n).
Second, design ideas
Set the first and second digits of the array to 2 of 63, and observe whether the result overflows.
Third, the source code
1 PackageCom.java.lianxi;2 3 ImportJava.util.Scanner;4 5 Public classLianxi4 {6 Public Static voidMain (string[] args)7 {8 intnum,i;9 LongSum=0;Ten LongMax; OneScanner cin=NewScanner (system.in); ASystem.out.print ("Please enter the length of the array:"); -num=cin.nextint (); - Longarray[]=New Long[num]; theArray[0]= (Long) Math.pow (2,63); -Array[1]= (Long) Math.pow (2,63); -Max=array[0]; - for(i=2;i<num;i++) + { - if((int) (Math.random () * *) ==0) + { AArray[i]= (Long) (Math.random () *100000000); at } - Else - { -array[i]=-(Long) (Math.random () *100000000); - } - } in for(i=0;i<num;i++) - { to if(sum<=0) + { -sum=Array[i]; the } * Else $ {Panax Notoginsengsum=sum+Array[i]; - } the if(sum>max) + { Amax=sum; the } + } - if(max== (Long) Math.pow (2,63)) $ { $SYSTEM.OUT.PRINTLN ("Large number Overflow"); -System.out.print ("sub-array and maximum value:" +max); - } the Else - {WuyiSystem.out.print ("sub-array and maximum value:" +max); the } - } Wu -}
Iv. Results of operation
Five, experience
Through testing, it is found that when overflow, the maximum number of sub-arrays and the constant is 2 63 times, that is, long can represent the largest integer, there is a large overflow, the result is not what we want.
We thought for a long time and did not think of any solution, because the data type can represent the number is so large, but if you want to get the correct results, we can not output a final result, you can output a few numbers to add,
But considering the number of additions to be controlled in 2 of the 63-time Square.
Also think of one is that the final result can be used as two variables to show that the high position in one of the variables, low placed in another variable, but we did not implement.
Software Engineering pair Development--one-dimensional maximal sub-array summation overflow problem