★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-pphvuzgx-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
On the first row, we write a 0
. Now in every subsequent row, we look at the previous row and replace each occurrence of 0
with 01
, and each occurrence of 1
with 10
.git
Given row N
and index K
, return the K
-th indexed symbol in row N
. (The values of K
are 1-indexed.) (1 indexed).github
Examples: Input: N = 1, K = 1 Output: 0 Input: N = 2, K = 1 Output: 0 Input: N = 2, K = 2 Output: 1 Input: N = 4, K = 5 Output: 1 Explanation: row 1: 0 row 2: 01 row 3: 0110 row 4: 01101001
Note:微信
N
will be an integer in the range [1, 30]
.K
will be an integer in the range [1, 2^(N-1)]
.在第一行咱們寫上一個 0
。接下來的每一行,將前一行中的0
替換爲01
,1
替換爲10
。spa
給定行數 N
和序數 K
,返回第 N
行中第 K
個字符。(K
從1開始)code
例子:htm
輸入: N = 1, K = 1 輸出: 0 輸入: N = 2, K = 1 輸出: 0 輸入: N = 2, K = 2 輸出: 1 輸入: N = 4, K = 5 輸出: 1 解釋: 第一行: 0 第二行: 01 第三行: 0110 第四行: 01101001
注意:blog
N
的範圍 [1, 30]
.K
的範圍 [1, 2^(N-1)]
.1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 if N == 1{ 4 return 0 5 } 6 7 return K % 2 == 0 ? (kthGrammar(N-1,K/2) == 0 ? 1 : 0 ):(kthGrammar(N-1,(K+1)/2) == 1 ? 1 : 0) 8 } 9 }
1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 var K = K 4 var res:Int = 0 5 while (K > 1) 6 { 7 K = (K % 2 == 1) ? K + 1 : K / 2 8 res ^= 1 9 } 10 return res 11 } 12 }
4msip
1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 var s = pow(Double(2), Double(N - 1)) 4 var flips = 0 5 var K = K 6 while (s > 2){ 7 if K > Int(s / 2) { 8 K -= Int(s / 2) 9 flips += 1 10 } 11 s /= 2 12 } 13 K -= 1 // K is either 2 or 1 14 if flips % 2 == 1 { 15 K = 1 - K 16 } 17 return K 18 } 19 }
8msget
1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 if K == 1 { 4 return 0 5 } 6 let halfCount = Int(pow(2.0, Double(N-2))) 7 let rm = K%halfCount 8 if K <= halfCount { 9 return kthGrammar(N-1, rm == 0 ? halfCount : rm) 10 } else { 11 return kthGrammar(N-1, rm == 0 ? halfCount : rm) == 0 ? 1 : 0 12 } 13 } 14 }