Skip to content

Commit 22a0572

Browse files
committed
Runtime 8 ms (Top 26.77%) | Memory 5.0 MB (Top 57.38%)
1 parent fba140e commit 22a0572

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed
Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
class Solution {
22
public:
33
int lastRemaining(int n) {
4-
int beg = 1, d = 1, len = n;
5-
bool fromleft = true;
6-
7-
while(len != 1 ) {
8-
if(fromleft || (len&1))
9-
beg += d;
10-
len >>= 1;
11-
d <<= 1;
12-
fromleft = !fromleft;
4+
bool left=true;
5+
int head=1,step=1;//step is the difference between adjacent elements.
6+
while(n>1){
7+
if(left || (n&1)){//(n&1)->odd
8+
head=head+step;
9+
}
10+
step=step*2;
11+
n=n/2;
12+
left=!left;
1313
}
14-
15-
return beg;
14+
return head;
1615
}
17-
};
16+
};

0 commit comments

Comments
 (0)