2016-07-10 3 views
0

数字だけで構成されるString値をLong値に変換しました。今度は、このLong値をn桁ごとに分割して、それらの「サブロング」をリストに追加します。どのようにn桁ごとに長い値を分割し、それをJavaのListに追加するのですか?

Long myLong = Long.valueOf(str).longValue(); 

私はすべてのn番目の数字でmyLongを分割し、List<Long>にそれらのセクションを追加します。

どうすればいいですか?

+0

あなたの質問は未定です。 「n」桁ごとに数値を分割することは、要件としては不十分です。グループ化を左右どちらから行うかを指定する必要があります。つまり、桁数が 'n'の正確な倍数でない場合はどうしますか?短いサブ結果は元の番号の左または右から来ますか?また、 'Long.MAX_VALUE'は19桁しかありません。あなたの「長い」数字には十分長い' Long'がありますか?代わりに 'BigInteger'を使うべきですか? –

答えて

-1

この作業を行うにはString.substring(...)を使用する必要があります。それとループはforです。 残りのコードを編集します。 編集された説明コメントも追加されました。

public static void main(String[] args) { 

    // Just for testing. 
    StringGrouper grouper = new StringGrouper(); 

    // Have tested for 2, 3, 4, and 5 
    List<Long> output = grouper.makeList(12892374897L, 4); 

    // Sends out the output. Note that this calls the List's toString method. 
    System.out.println(output); 
} 

/** 
* @param l 
* @param spacing 
*/ 
private List<Long> makeList(long l, int spacing) { 

    List<Long> output = new ArrayList<>(Math.round(l/spacing)); 
    String longStr = String.valueOf(l); 
    // System.err.println(longStr); 

    for (int x = 0; x < longStr.length(); x++) { 

     // When the remainder is 0, that's where the grouping starts and ends 
     if (x % spacing == 0) { 

      // If it does not overflow, send it in 
      if ((x + spacing) < longStr.length()) { 

       String element = longStr.substring(x, x + spacing); 
       // System.err.println(element); 
       output.add(Long.parseLong(element)); 

      } else { 
       // If it does overflow, put in the remainder 
       output.add(Long.parseLong(longStr.substring(x, longStr.length()))); 
      } 
     } 
    } 

    return output; 
} 
関連する問題