Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

简单的位移实现

Posted by smilerxz at 2009-08-15 18:13:40 on Problem 2453
int solve(int n) {
    int low = 0;
    while (! (n & 1 << low)) low++;
    int high = low;
    while (n & 1 << high) high++;
    return n & 0x7fffffff << high | 1 << high | 0x7fffffff >> 31 - (high - low - 1);
}

1. 注意优先级,从高到低依次为: - ; << >> ;  & ; |
2. low 为从低位(从0起)到高位第一个为1的位, high为从从low起到高位第一个为0的位
3. n & 0x7fffffff << high : 将低于high的位全部置为0
   ... | 1 << high : 将high位置为1(开始为0)
   ... | 0x7fffffff >> 31 - (high - low - 1) : 将最低的(high-low-1)个位上全部置为1

如输入6 是 ...0110, low = 1, high = 3, 将第3位置为1,0~2位置为0,将最低的1(=3-1-1)个位全部置为1即为1001
如输入10 是...1010, low = 1, high = 2, 将第2位置为1,0~1位置为0,将最低的0(=2-1-1)个位全部置为1(实际上最后一步未改变数值),即为1100

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator