ikemonn's blog

技術ネタをちょこちょこと

【TopCoder】SRM 154 DIV2 Lv.1

問題文概略

商品の仕入れ値と売値から売上を算出する問題

書いたコード

public class ProfitCalculator {

    public int percent(String[] items) {

        double cost = 0;
        double price = 0;
        double margin = 0;

        for(int i = 0; i < items.length; i++) {
            price += Double.parseDouble(items[i].substring(0, 6));
            cost += Double.parseDouble(items[i].substring(7, 13));
        }
        margin = price - cost;
        return (int) Math.floor((margin / price) * 100);
    }

}

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

public class ProfitCalculator {

    public int percent(String[] items) {

        double cost = 0;
        double price = 0;
        double margin = 0;

        for(String s : items) {
            String[] split = s.split(" ",0);
            price += Double.parseDouble(split[0]);
            cost += Double.parseDouble(split[1]);
        }
        return (int) ((price - cost) * 100 / price);
    }

}

雑感

文字列分割方法

1.splitを使う

public String[] split[](String regex, int limit)

文字列をregexで指定された正規表現に一致する位置で分割する。

  • regex:パターン(正規表現)
  • limit:パターンの適応回数。
    • 0ならパターンの適用回数と配列の長さは制限されず、後続の空文字列は破棄
    • 負の数ならパターンの適用回数と配列の長さは制限されない。

2.substringを使う

public String substring(int beginIndex, int endIndex)

beginIndex〜endIndex-1にある文字までを返す。

  • beginIndex:開始インデックス(この値を含む)
  • endIndex:終了インデックス(この値は含まない)