Class Solution

java.lang.Object
g0401_0500.s0481_magical_string.Solution

public class Solution extends Object
481 - Magical String.<p>Medium</p> <p>A magical string <code>s</code> consists of only <code>'1'</code> and <code>'2'</code> and obeys the following rules:</p> <ul> <li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>'1'</code> and <code>'2'</code> generates the string <code>s</code> itself.</li> </ul> <p>The first few elements of <code>s</code> is <code>s = &quot;1221121221221121122\u2026\u2026&quot;</code>. If we group the consecutive <code>1</code>&rsquo;s and <code>2</code>&rsquo;s in <code>s</code>, it will be <code>&quot;1 22 11 2 1 22 1 22 11 2 11 22 ......&quot;</code> and the occurrences of <code>1</code>&rsquo;s or <code>2</code>&rsquo;s in each group are <code>&quot;1 2 2 1 1 2 1 2 2 1 2 2 ......&quot;</code>. You can see that the occurrence sequence is <code>s</code> itself.</p> <p>Given an integer <code>n</code>, return the number of <code>1</code>&rsquo;s in the first <code>n</code> number in the magical string <code>s</code>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> n = 6</p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong> The first 6 elements of magical string s is &ldquo;122112&rdquo; and it contains three 1&rsquo;s, so return 3.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> n = 1</p> <p><strong>Output:</strong> 1</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= n <= 10<sup>5</sup></code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • magicalString

      public int magicalString(int n)