🌕🌑🌑🌑🌑
# 題目連結
- 題目連結
- Online Judge
- uDebug
# 題目說明
Time limit: 3.000 seconds
# 題目
Given a number, we can form a number chain by
- arranging its digits in descending order
- arranging its digits in ascending order
- subtracting the number obtained in (2) from the number obtained (1) to form a new number
- and repeat these steps unless the new number has already appeared in the chain
Note that 0 is a permitted digit. The number of distinct numbers in the chain is the length of the chain. You are to write a program that reads numbers and outputs the number chain and the length of that chain for each number read.
# Input
The input consists of a sequence of positive numbers, all less than , each on its own line, terminated by ‘0’
. The input file contains at most 5000
numbers.
# Output
The output consists of the number chains generated by the input numbers, followed by their lengths exactly in the format indicated below. After each number chain and chain length, including the last one, there should be a blank line. No chain will contain more than 1000
distinct numbers.
# Sample Input
123456789
1234
444
0
# Sample Output
Original number was 123456789
987654321 - 123456789 = 864197532
987654321 - 123456789 = 864197532
Chain length 2Original number was 1234
4321 - 1234 = 3087
8730 - 378 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
Chain length 4Original number was 444
444 - 444 = 0
0 - 0 = 0
Chain length 2
# 解題技巧
利用到各種字串技巧:
- String 轉 char []:
char[] c = str.toCharArray();
- char [] 排序:
Arrays.sort(c);
- char [] 轉 String:
String str = new String(c);
- String 倒轉:
StringBuilder sb = new StringBuilder(str);
String reverseStr = sb.reverse().toString();
- String 轉 int:
int reverseInt = Integer.parseInt(reverseStr);
# Solution
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
String s = sc.next(); | |
Set<String> set = new HashSet<>(); | |
while (!s.equals("0")) { | |
int count = 0; | |
System.out.println("Original number was " + s); | |
set = new HashSet<>(); | |
while (true) { | |
char[] c = s.toCharArray(); | |
Arrays.sort(c); | |
String asc = new String(c); | |
StringBuilder sb = new StringBuilder(asc); | |
String des = sb.reverse().toString(); | |
int desInt = Integer.parseInt(des); | |
int ascInt = Integer.parseInt(asc); | |
int next = desInt - ascInt; | |
s = Integer.toString(next); | |
System.out.println(desInt + " - " + ascInt + " = " + next); | |
count++; | |
if(set.contains(s)){ | |
break; | |
}else{ | |
set.add(s); | |
} | |
} | |
System.out.println("Chain length " + count); | |
System.out.println(""); | |
s = sc.next(); | |
} | |
sc.close(); | |
} | |
} |
單字
** **
!! !!
片語 & 搭配詞
!! !!