A題之字符串末尾補0

按要求分解字符串,輸入兩個數M,N;M代表輸入的M串字符串,N代表輸出的每串字符串的位數,不夠補0。例如:輸入2,8, “abc” ,“123456789”,則輸出爲“abc00000”,“12345。
678“,”90000000”

思路:
1)對每一個字符串的長度取模length%N,在字符串末尾補(N-length%N)個0
2)將所有字符串補0後的字符串拼接在一起
3)拼接後的字符串按照M長度,分段打印出來即可

Java代碼實現如下:

import java.util.Scanner;
public class Main
{
     public static void main(String[] args)
     {
          Scanner cin=new Scanner(System.in);
          int m=0,n=0;
          while(cin.hasNextInt())
          {
               m=cin.nextInt();
               n=cin.nextInt();
               break;
          }
 
          int i=0;
          StringBuffer sb=new StringBuffer();
          while(i!=m&&cin.hasNext())
          {
               i++;
               String temp=cin.next();
               if (temp.length()%n!=0)
               {
                    sb.append(temp);
                    int len=n-temp.length()%n;
                    for (int j = 0; j < len; j++)
                    {
                         sb.append("0");
                    }
               }
               else {
                    sb.append(temp);
               }
          }
 
          int k=0;
          for (int j = 0; j < sb.length(); j++)
          {
               k++;
               System.out.print(sb.charAt(j));
               if (k==n)
               {
                    System.out.print(" ");
                    k=0;
               }
          }
     }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章