xyz 的个人资料为而不争日志列表 工具 帮助
2009/6/23

看到的有道的某题及做的解法

看到的有道的某题。


Problem Statement

      

一个二进制序列由下面的伪代码生成:

string A = "0"

While (A的长度小于等于n)

    创建一个和A一样长度的字符串B

    For i=0,1,...length(A)-1

        If (i 是完全平方数)

            B[i] = 1-A[i]

        Else

            B[i] = A[i]

    A = A + B (即将B拼接在A后面)

End While

Return A

请注意,在上面的伪代码中,A[i]B[i]分别表示字符串AB中下标为i的字符(下标编号从0开始)。对"完全平方数"的定义是,对于整数i,存在整数j,使得i= j *j,则称i为完全平方数。

下面具体说明序列生成的过程:如果n=7,则在每一轮迭代中,A的取值依次为:0, 01, 0110, 01101010,所以最终产生的二进制序列就是0,1,1,0,1,0,1,0

请返回上述序列中下标为n的数字(该序列的下标从0开始)

Definition

      

Class:

BinarySequence

Method:

getValue

Parameters:

int

Returns:

int

Method signature:

int getValue(int n)

(be sure your method is public)

      

 

Constraints

-

n 的取值大于等于0,小于等于2,000,000,000

Examples

0)

 

      

7

Returns: 0

原因参见题目描述。

1)

2

Returns: 1

2)      

8

Returns: 1

这一次,生成的序列为0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0.

3)      

11

Returns: 0

4)       

10

Returns: 1  

5)      

15

Returns: 0

 

 

耗费三五小时,作出一解法:

unsigned int getValue(const unsigned int & n)
{
 unsigned int truen=n+1;
 unsigned int pow2=1;
 //unsigned int pow2p=0;
 unsigned int changetimes=0;
 unsigned int currentPerfectsquare=0;
 unsigned int currentPerfectsquarebase=0;
 unsigned int lastcn=0xffffffff;
 while (pow2<=n)
 {
  unsigned int cn=n%pow2;
  if (lastcn!=cn)
  {
   while (currentPerfectsquare<cn)
   {
    currentPerfectsquare=++currentPerfectsquarebase*currentPerfectsquarebase;
   }
   if (currentPerfectsquare==cn)
   {
    changetimes++;
   }
  }
  lastcn=cn;
  pow2*=2;
  //pow2p++;
 }
 return changetimes%2;
}

为c/c++代码。算法复杂度O(log(n)),而且算法复杂度中的隐含系数也尽可能的减少了。

昨晚解决,今早发日志。

经测试比目前为止所见的算法都快……

评论 (1)

请稍候...
很抱歉,您输入的评论太长。请缩短您的评论。
您没有输入任何内容,请重试。
很抱歉,我们当前无法添加您的评论。请稍后重试。
若要添加评论,需要您的家长授予您相应权限。请求权限
您的家长禁用了评论功能。
很抱歉,我们当前无法删除您的评论。请稍后重试。
您已超过了一天之内允许提供的评论数上限。请在 24 小时后重试。
因为我们的系统表明您可能在向其他用户提供垃圾评论,您的帐户已禁用了评论功能。如果您认为我们错误地禁用了您的帐户,请联系 Windows Live 支持部门
完成下面的安全检查,您提供评论的过程才能完成。
您在安全检查中键入的字符必须与图片或音频中的字符一致。

若要添加评论,请使用您的 Windows Live ID 登录(如果您使用过 Hotmail、Messenger 或 Xbox LIVE,您就拥有 Windows Live ID)。登录


还没有 Windows Live ID 吗?请注册

plyxyz发表:
补充一句,其实除了函数出入口以外,是c/c++/c#/java/...通用的……
7 月 20 日

引用通告

此日志的引用通告 URL 是:
http://ply-xyz.spaces.live.com/blog/cns!12E36C1BED3A8855!317.trak
引用此项的网络日志