首页 > 代码库 > Count And Say
Count And Say
Problem
Implement Count And Say function. For example, first, let user input a number, say 1. Then, the function will generate the next 10 numbers which satisfy this condition: ,1, 11,21,1211,111221,312211...
explanation: first number 1, second number is one 1, so 11. Third number is two 1(previous number), so 21. next number one 2 one 1, so 1211 and so on...
Solution
public String countAndSay(int n) { if (n <= 0) return ""; String curRes = "1"; int start = 1; while (start < n) { StringBuffer sb = new StringBuffer(); int cnt = 1; for (int i = 1; i < curRes.length(); i++) { if (curRes.charAt(i) == curRes.charAt(i - 1)) { cnt++; } else { sb.append(cnt); sb.append(curRes.charAt(i - 1)); cnt = 1; } } sb.append(cnt); sb.append(curRes.charAt(curRes.length() - 1)); curRes = sb.toString(); start++; } return curRes;}
Count And Say
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。