Created
May 2, 2021 10:07
-
-
Save Nkwachi-N/b0962619522f1099c6c5ca99b12451d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static int[] algoFunc(int[] numArray) { | |
| int totalMultiplication = 1; | |
| for(int num : numArray) { | |
| try{ | |
| totalMultiplication = totalMultiplication * num; | |
| }catch (ArithmeticException e){ | |
| totalMultiplication = 0; | |
| break; | |
| } | |
| } | |
| int arrayLength = numArray.length; | |
| int[] newArray = new int[arrayLength]; | |
| for(int i = 0 ; i < arrayLength ; i++) { | |
| if(numArray[i] == 0) { | |
| int multiplier = 1; | |
| //This comment encloses the short code I could come up with to solve the algorithm but I believe | |
| for(int j = 0 ; j < arrayLength ; j++) { | |
| if(j == i) continue; | |
| try{ | |
| multiplier = multiplier * numArray[j]; | |
| }catch (ArithmeticException e) { | |
| multiplier = 0; | |
| break; | |
| } | |
| } | |
| //it's madly inefficient when the array does not contain 0. | |
| //Hence my solution. | |
| newArray[i] = multiplier; | |
| continue; | |
| } | |
| try { | |
| newArray[i] = totalMultiplication /numArray[i]; | |
| }catch (ArithmeticException e){ | |
| newArray[i] = 0; | |
| } | |
| } | |
| return newArray; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you @meekg33k for conducting Algrorithn Fridays.
I currently can't think of any better solution, I'm looking forward to the published solution.
It'll be really informative and interesting to see the best eay to solve this without a nested loop.