zoukankan      html  css  js  c++  java
  • 1087 1 10 100 1000

    题目来源: Ural 1209
    基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
     
    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,再匹配就好。

    注意打表时最好用bool类型定义数组否则可能会爆内存。

    第二种就是直接判断啦,判断方法与打表一样,理论上比打表要快。

    杨辉三角数判定公式(等差数列求和公式):

    i*(i+1)/2==n-1

    令t=(int)sqrt(2.0*(n-1)),则只要满足t*(t+1)==2*(n-1)即为1.

    附AC代码:

     1 #include<iostream>
     2 #include<cmath>
     3 using namespace std;
     4 
     5 int solve(int x){
     6     int t=2*(x-1);
     7     t=sqrt(t);
     8     if(2*(x-1)==t*(t+1))
     9     return 1;
    10     return 0;
    11 }
    12 
    13 int main(){
    14     int n,x;
    15     cin>>n;
    16     while(n--){
    17         cin>>x;
    18         cout<<solve(x)<<endl;
    19     }
    20     return 0;
    21 }

    打表代码:

     1 #include<iostream>
     2 #include<cmath>
     3 using namespace std;
     4 
     5 const int N=100000010;
     6 
     7 bool a[N];
     8 
     9 void init(){
    10     int i=0;
    11     while(1){
    12         int t=i*(i+1)/2+1;
    13         if(t>=N) break;
    14         a[t]=1;
    15         i++;
    16     }
    17 }
    18 
    19 int main(){
    20     init();
    21     int n,x;
    22     cin>>n;
    23     while(n--){
    24         cin>>x;
    25         cout<<a[x]<<endl;
    26     }
    27     return 0;
    28 }
  • 相关阅读:
    Netty实现Http客户端
    Netty实现Http服务端
    Netty实现Tcp客户端
    Netty实现Tcp服务端
    MySQL进阶系列:一文详解explain
    spring boot 获取运行时的yml里的active配置
    eureka 注册中心添加认证
    zuul 负载
    jenkins spring cloud
    秒杀系统如何设计?
  • 原文地址:https://www.cnblogs.com/Kiven5197/p/5781993.html
Copyright © 2011-2022 走看看