讓咱們用字母 B
來表示「百」、字母 S
表示「十」,用 12...n
來表示不爲零的個位數字 n
(n < 1000),換個格式來輸出任一個不超過 3 位的正整數。例如 234
應該被輸出爲 BBSSS1234
,由於它有 2 個「百」、3 個「十」、以及個位的 4。html
每一個測試輸入包含 1 個測試用例,給出正整數 n(<)。java
每一個測試用例的輸出佔一行,用規定的格式輸出 n。ios
234
BBSSS1234
23
SS123
給出的數字至多隻有3位數,因此能夠建立一個大小爲3的數組,分別存放百位、十位、個位。最後利用循環輸出就能夠了數組
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int n; 7 int arr[3]; 8 cin >> n; 9 10 for (int i = 2; i >= 0; --i) 11 { 12 arr[i] = n % 10; 13 n /= 10; 14 } 15 16 for (int i = 0; i < arr[0]; ++i) 17 { 18 cout << "B"; 19 } 20 for (int i = 0; i < arr[1]; ++i) 21 { 22 cout << "S"; 23 } 24 for (int i = 1; i <= arr[2]; ++i) 25 { 26 cout << i; 27 } 28 return 0; 29 }
思路1:測試
同C++作法:建立一個長度爲3的數組,分別存放百位、十位、個位。flex
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 int[] arr = new int[3]; 7 int n = input.nextInt(); 8 for (int i = 2; i >= 0; --i) { 9 arr[i] = n % 10; 10 n /= 10; 11 } 12 for (int i = 0; i < arr[0]; ++i) { 13 System.out.print("B"); 14 } 15 for (int i = 0; i < arr[1]; ++i) { 16 System.out.print("S"); 17 } 18 for (int i = 1; i <= arr[2]; ++i) { 19 System.out.print(i); 20 } 21 } 22
思路2:spa
對輸入的數字n進行分辨得出:百位 [ a ]、十位 [ b ]、個位 [ c ]。code
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 int n = input.nextInt(); 7 int a = 0, b = 0, c = 0; 8 if (n >= 100) { 9 a = n / 100; 10 b = (n % 100) / 10; 11 c = n % 10; 12 } 13 if (n >= 10 && n < 100) { 14 b = n / 10; 15 c = n % 10; 16 } 17 if (n >= 1 && n < 10) { 18 c = n; 19 } 20 for (int i = 0; i < a; ++i) { 21 System.out.print("B"); 22 } 23 for (int i = 0; i < b; ++i) { 24 System.out.print("S"); 25 }28 for (int i = 1; i <= c; ++i) {31 System.out.print(i); 32 } 33 } 34 }