請把紙條豎着放在桌⼦上,而後從紙條的下邊向上⽅對摺,壓出摺痕後再展 開。此時有1條摺痕,突起的⽅向指向紙條的背⾯,這條摺痕叫作「下」摺痕 ;突起的⽅向指向紙條正⾯的摺痕叫作「上」摺痕。若是每次都從下邊向上⽅ 對摺,對摺N次。請從上到下計算出全部摺痕的⽅向。java
給定折的次數n,請返回從上到下的摺痕的數組,若爲下摺痕則對應元素爲"down",若爲上摺痕則爲"up".數組
1 返回:["down"]
連接測試
首先我用手頭的紙張進行實驗,進行對摺1,2,3,4次,發現了一些規律。code
package codewars.jul; import java.util.LinkedList; public class FoldPaper { private static String[] next(String[] previous, int fold) { int n = (int) Math.pow(2, fold); String[] rs = new String[n + (n - 1)]; int cur = 0; boolean down = true; for (int i = 0; i < rs.length; i++) { if (i % 2 == 1) { rs[i] = previous[cur++]; } } for (int i = 0; i < rs.length; i++) { if (rs[i] == null) { if (down) { rs[i] = "down"; down = false; } else { rs[i] = "up"; down = true; } } } return rs; } public String[] foldPaper(int n) { if (n < 1) { return new String[0]; } LinkedList<String> list = new LinkedList<String>(); int pieces = 0; int count = 0; if (n == 1) { list.add("down"); pieces = 2; count = 1; return list.toArray(new String[0]); } else { return next(foldPaper(n - 1), n - 1); } } public static void main(String[] args) { FoldPaper obj = new FoldPaper(); String[] arr = obj.foldPaper(4); for (String str : arr) { System.out.print(str + " "); } } }