我在算法類中,我們需要製作一個程序,通過將它們加載到鏈表中來添加很長的數字。我在網上看到很多例子,只使用兩個鏈表,但我的需求不止兩個。如何在我的java代碼中刪除這些嵌套的for-loops?
import java.util.*;
public class longNumbersLinkedListCompleted
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String longNumber = "";
LinkedList mainList = new LinkedList();
LinkedList sumList = new LinkedList();
LinkedList temp = null;
//declare other variables
int sum = 0;
int carry= 0;
int maxWidth = 0;
System.out.println("Enter a Number");
longNumber = stdIn.nextLine();
//repeatedly input longNumbers, using -1 to indicate that you are done
while(!longNumber.equals("-1")){
//add a new LinkedList at the beginning of the mainList
mainList.addFirst(new LinkedList());
//use get(0) to set temp to be this new LinkedList
temp = (LinkedList) mainList.get(0);
//for each character in your longNumber, subtract 48 to get the digit and then add it
//at the beginning of temp
for (int i = 0; i < longNumber.length(); i++){
temp.addFirst((int)(longNumber.charAt(i)-48));
}
//keep track of maxWidth, the number of digits of the widest longNumber input so far
if(maxWidth < longNumber.length()){
maxWidth = longNumber.length();
}
System.out.println("Enter a Number");
longNumber = stdIn.nextLine();
}
//make maxWidth passes
//initialize carry to be 0
//in each pass, loop through all of the LinkedLists in mainList
//for each one, let temp be the Linked List for one longNumber
//if temp is not empty, remove its first entry and add to the sum
for(int i = 0; i < maxWidth; i++){
sum = 0;
for(int j = 0; j < mainList.size(); j++){
temp = (LinkedList)mainList.get(j);
if(temp.size() > 0){
sum += (int)temp.removeFirst();
}
}
//add sum%10 at the beginning of sumList
//set carry equal to sum/10 (integer division)
sumList.addFirst((sum+carry)%10);
carry = (sum + carry)/10;
}
//Now ready for output
//if carry at the end of processing is not 0, print it and stay on the same line
//repeatedly remove one digit from the beginning of sumList until all have been removed
//for each, add a 48 to get a character and print it out on the same line
if(carry != 0){
System.out.print(carry);
}
for(int i = sumList.size(); i > 0; i--){
System.out.print((char)((int)sumList.removeFirst()+48));
}
//remove the digits from sumList until empty
}//end main
} //結束類
的意見是從教授,所以它有點聽起來像他想的嵌套的循環,但在當今一流他提到不使用他們,因爲整個類是關於使代碼更好,使用O(n^2)的東西似乎是不直觀的。
我很感謝你們的幫助!
也許你應該在[代碼評論](http://codereview.stackexchange.com/)上提出這個問題 – BackSlash
你應該*絕對*不要做的一件事是[使用原始類型](http://stackoverflow.com /問題/ 2770321 /什麼 - 是 - 一 - 生型和原因,不應該,我們使用 - 它)。所有這些演員都是不必要的。 –
我可以看到避免嵌套for循環的唯一方法是在讀取長整數時進行轉置,即在您正在處理時在while循環中構建和。 –