解釋:如果輸入字符串是“hello worlds”,則輸出將為 2?!澳愫谩边@個詞的長度 = 5“世界”一詞的長度 = 6將它們的長度相加得到總長度 = 5+6 = 11這不是一個數(shù)字,所以不斷添加所有數(shù)字,直到我們得到一個數(shù)字,即 1+1=2 因此,單個數(shù)字是 = 2(作為答案/輸出)。我嘗試使用我的代碼如下:import java.util .*;class Codestring { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter word"); String word = sc.nextLine(); int len2 = 0, len1 = 0, count = 0; for (int i = 0; i < word.length(); i++) { if (word.charAt(i) == ' ') { len2 = count; System.out.println(len2); count = 0; } else { count++; } } len1 = count; System.out.println(len1); int c = len1 + len2; System.out.println(c); ArrayList<Integer> array = new ArrayList<Integer>(); do { array.add(c % 10); c /= 10; } while (c > 0); System.out.println(array); while (array.size() >= 2) { array = reduce(array); return array; } } private static ArrayList<Integer> reduce(ArrayList<Integer> array) { for (int i = 0; i < array.size(); i++) { array = array[i] + array[i + 1]; } return array; }}我達到了我的輸出:輸入單詞你好世界5611[1, 1]
添加回答
舉報
0/150
提交
取消