exercism————Raindrops

题目:

exercism————Raindrops_第1张图片

解法1:

public class Raindrops {

	String convert (int number) {
		String output = "";

		if (number % 3 == 0) {
			output += "Pling";
		}

		if (number % 5 == 0) {
			output += "Plang";
		}

		if (number % 7 == 0) {
			output += "Plong";
		}

		if (output.isEmpty()) {
			return Integer.toString(number);
		} else {
			return output;
		}
	}
}

解法2:

public class Raindrops {

    static String convert(int input) {
        StringBuilder builder = new StringBuilder();
        if (input % 3 == 0) builder.append("Pling");
        if (input % 5 == 0) builder.append("Plang");
        if (input % 7 == 0) builder.append("Plong");
        return builder.length() > 0 ? builder.toString() : String.valueOf(input);
    }

}

总结:

解法一是博主自己的解法,通过阅读过较多别人代码,挑选出解法二,此问题使用设计到字符串的添加改动,使用StringBuilder类比较合适。

你可能感兴趣的:(Exercism)