0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SRM149 div2 250

Posted at

問題文概略

与えられたドルとセント数を組み合わせて、"$1,234.05"のように表示せよ。
ドル:最初に"$"が付き、3桁ごとにカンマがつく。
セント:最初に"."が付き、1桁の場合0+数字となる。

書いたコード

public class FormatAmt {

	public String amount(int dollars, int cents) {
		int n=0;
		int j=1;
		String s = "";
		String sDollars = String.valueOf(dollars);
		String sCents = String.valueOf(cents);
		//ドルに,をつける
		for(int i=sDollars.length()-1; i>=0; i--){
			s += sDollars.charAt(i);
			if(j%3==0 && j !=sDollars.length() ) {
				s+=",";
			}
			j++;
		}
		StringBuffer ans = new StringBuffer(s);
		//セントに0をつける
		if(sCents.length() != 2) {
			sCents = "0" + sCents;
		}
		return "$"+ans.reverse()+"."+sCents;

	}

}

他の参加者のコードを読んで修正した

public class FormatAmt {

	public String amount(int dollars, int cents) {

		String s = "";
		int i = 0;
		if(dollars == 0) {
			s += "0";
		}
		while(dollars > 0) {
			int mod = dollars % 10;
			dollars /= 10;
			i++;
			if(i % 3 == 0 && dollars != 0) {
				s = "," + mod + s;
			} else {
				s = mod + s;
			}
		}
		String c = "";
		if(cents < 10) {
			c = "0" + cents;
		} else {
			c += cents;
		}
		return "$" + s + "." + c;
	}

}

雑感

ドルの3桁区切りを実装するのに、

「数字を逆順に並び替える」
↓
「左から3桁づつにカンマをつける」
↓
「もう一度逆に並び替える」

と考えたのだが、

10で割った余りを求めて並べる
↓
3回おきにカンマを加える

とすれば楽に実装できたんだな。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?