LeetCode | 779. K-th Symbol in Grammar数学原理题

Onthe first row, we write a 0. Now in every subsequent row, we look at the previous rowand replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

Givenrow N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).

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:

1.      N will be an integer in the range [1, 30].

2.      K will be an integer in the range [1, 2^(N-1)].

这一题给你一个初始的0,每次按照0变成01,1变成10的规律来分析,问你第N行,第K列的数字为多少

这一题通过观察能够发现规律,第n行为第n-1行的全部数字取反之后加到第n-1行的后面,根据这个规律分析可以得到,假设第n-1有num(n-1)个数字,第n-1行第k个数字等于第n行k+ num(n-1)个数字取反,同样的,第n行第k个数字等于第n-1行第(k-1)%num(n-1)+1个数字取反(之所以要加一在减一是因为%是取模操作,范围是0到n-1,而这里的k是从1开始取),

进行kn= (kn-1)%num(n-1)+1,这个操作直到k<=8,就能够直接得到结果

class Solution {
public:
 int getTheNuwNum(int num)
{
	int tmp = 8;
	while (tmp * 2 < num) tmp *= 2;
	return (num - 1) % tmp + 1;
}
int kthGrammar(int N, int K) {
	int theMark[8] = { 0,1,1,0,1,0,0,1 };
	int tmp = K; int count = 0;
	while (tmp > 8)
	{
		tmp = getTheNuwNum(tmp);
		count++;
	}
	if (count % 2 == 0)
	{
		return theMark[tmp - 1];
	}
	else
	{
		return theMark[tmp - 1]==0?1:0;
	}
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值