Easy Answer in Java


  • 0
    Y

    This is the Java I wrote. It might not be an elegant one, but it's pretty easy to understand.
    I simulate the way the nth sequence got generated.

    public class Solution {
        public String countAndSay(int n) {
            String ans = "";
            String ans1 ="1";
            int num;
            int cnt;
            for( int i = 2 ; i <= n ;i++){
                num = Character.getNumericValue(ans1.charAt(0));
                cnt=0;
                for(int j = 0; j < ans1.length(); j++){
                    if(num == Character.getNumericValue(ans1.charAt(j)))
                        cnt++;
                    else{
                        ans = ans + Integer.toString(cnt)+ Integer.toString(num);
                        cnt = 1;
                        num = Character.getNumericValue(ans1.charAt(j));
                    }
                }
                ans = ans + Integer.toString(cnt)+ Integer.toString(num);
                ans1 = ans;
                ans="";
            }
            return ans1;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.