美文网首页
每日一练47——Java重复的字符串(8kyu)

每日一练47——Java重复的字符串(8kyu)

作者: 砾桫_Yvan | 来源:发表于2018-07-16 10:13 被阅读0次

    题目

    编写一个函数repeatStr,该函数会string精确重复给定的字符串n。

    repeatStr(6, "I") // "IIIIII"
    repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"
    

    测试用例:

    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    
    public class SolutionTest {
        @Test public void test4a() {
            assertEquals("aaaa", Solution.repeatStr(4, "a"));
        }
        @Test public void test3Hello() {
            assertEquals("HelloHelloHello", Solution.repeatStr(3, "Hello"));
        }
        @Test public void test5empty() {
            assertEquals("", Solution.repeatStr(5, ""));
        }
        @Test public void test0kata() {
            assertEquals("", Solution.repeatStr(0, "kata"));
        }
        @Test public void testNegativeRepeat() {
            assertEquals("", Solution.repeatStr(-10, "kata"));
        }
    }
    

    解题

    My:

    public class Solution {
        public static String repeatStr(final int repeat, final String string) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < repeat; i++) {
                sb.append(string);
            }
            return sb.toString();
        }
    }
    

    后记

    大家的想法还是惊人的相似,甚至是变量的取名,也有不一样的,所以有一点值得说,如果传入值为空怎么办,题目没有特别说明不需要考虑输入验证。

    相关文章

      网友评论

          本文标题:每日一练47——Java重复的字符串(8kyu)

          本文链接:https://www.haomeiwen.com/subject/vwyvpftx.html