[51nod] 1087 1 10 100 1000
阿新 • • 發佈:2017-06-25
true ret namespace sof nbsp class 類型 color nod
1,10,100,1000...組成序列1101001000...,求這個序列的第N位是0還是1。
Input
第1行:一個數T,表示後面用作輸入測試的數的數量。(1 <= T <= 10000)
第2 - T + 1行:每行1個數N。(1 <= N <= 10^9)
Output
共T行,如果該位是0,輸出0,如果該位是1,輸出1。
Input示例
3
1
2
3
Output示例
1
1
0
一開始的做法是先對1的位數進行打表,然後進行二分
#include <iostream> #include <stdio.h> #include <cstring> usingnamespace std; const int maxn = 100100; int One[maxn]; void preOne() { int i = 1; One[0] = 1; while (i < maxn) { One[i] = One[i-1]+i; i++; } } bool Find(int x) { int l = 0, r = maxn-1, mid; while (l <= r) { mid = (l+r)>>1; if (One[mid] > x) r= mid-1; else if (One[mid] < x) l = mid+1; else return true; } return false; } int main() { //freopen("1.txt", "r", stdin); preOne(); int T; scanf("%d", &T); while (T--) { int n; scanf("%d", &n); if (Find(n)) printf("1\n"); else printf("0\n"); } return 0; }
直接用bool類型對i位置是不是1進行打表也可以
其實是有規律的
1 = 1
2 = 1 + (1)
4 = 1 + (1+2)
7 = 1 + (1+2+3)
.....
即 X*(X-1)/2 + 1 == n有解
另t = (int)sqrt(2*n-2) t*(t+1)==2*(n-1)成立時有解
#include <iostream> #include <stdio.h> #include <math.h> using namespace std; int main() { int T; scanf("%d", &T); while (T--) { int n; scanf("%d", &n); int t = (int)sqrt(2*(n-1)); if (t*(t+1) == 2*(n-1)) printf("1\n"); else printf("0\n"); } return 0; }
[51nod] 1087 1 10 100 1000