codewars解题笔记---If you can't sleep, just count sheep!!

题目

Given a non-negative integer, 3 for example, return a string with a murmur: "1 sheep...2 sheep...3 sheep...". Input will always be valid, i.e. no negative integers.

解析

传入一个数字n,输出1 sheep...2 sheep...n sheep...

我的答案

 public static String countingSheep(int num) {
    //Add your code here
    StringBuilder stringBuilder = new StringBuilder();
        for (int i=1;i<=num;i++){
            stringBuilder.append(i+" sheep...");
        }
        return stringBuilder.toString();
  }

最好的答案

  public static String countingSheep(int num) {
    return IntStream.rangeClosed(1, num)
                    .mapToObj(i -> i + " sheep...")
                    .collect(Collectors.joining());
  }

猜你喜欢

转载自blog.csdn.net/z_victoria123/article/details/86527045