我打印出了1 - 100
n = 1, ans = 1
n = 2 ans = 2
n = 3 ans = 2
n = 4 ans = 4
n = 5 ans = 2
n = 6 ans = 4
n = 7 ans = 6
n = 8 ans = 8
n = 9 ans = 2
n = 10 ans = 4
n = 11 ans = 6
n = 12 ans = 8
n = 13 ans = 10
n = 14 ans = 12
n = 15 ans = 14
n = 16 ans = 16
n = 17 ans = 2
n = 18 ans = 4
n = 19 ans = 6
n = 20 ans = 8
n = 21 ans = 10
n = 22 ans = 12
n = 23 ans = 14
n = 24 ans = 16
n = 25 ans = 18
n = 26 ans = 20
n = 27 ans = 22
n = 28 ans = 24
n = 29 ans = 26
n = 30 ans = 28
n = 31 ans = 30
n = 32 ans = 32
n = 33 ans = 2
n = 34 ans = 4
n = 35 ans = 6
n = 36 ans = 8
n = 37 ans = 10
n = 38 ans = 12
n = 39 ans = 14
n = 40 ans = 16
n = 41 ans = 18
n = 42 ans = 20
n = 43 ans = 22
n = 44 ans = 24
n = 45 ans = 26
n = 46 ans = 28
n = 47 ans = 30
n = 48 ans = 32
n = 49 ans = 34
n = 50 ans = 36
n = 51 ans = 38
n = 52 ans = 40
n = 53 ans = 42
n = 54 ans = 44
n = 55 ans = 46
n = 56 ans = 48
n = 57 ans = 50
n = 58 ans = 52
n = 59 ans = 54
n = 60 ans = 56
n = 61 ans = 58
n = 62 ans = 60
n = 63 ans = 62
n = 64 ans = 64
n = 65 ans = 2
n = 66 ans = 4
n = 67 ans = 6
n = 68 ans = 8
n = 69 ans = 10
n = 70 ans = 12
n = 71 ans = 14
n = 72 ans = 16
n = 73 ans = 18
n = 74 ans = 20
n = 75 ans = 22
n = 76 ans = 24
n = 77 ans = 26
n = 78 ans = 28
n = 79 ans = 30
n = 80 ans = 32
n = 81 ans = 34
n = 82 ans = 36
n = 83 ans = 38
n = 84 ans = 40
n = 85 ans = 42
n = 86 ans = 44
n = 87 ans = 46
n = 88 ans = 48
n = 89 ans = 50
n = 90 ans = 52
n = 91 ans = 54
n = 92 ans = 56
n = 93 ans = 58
n = 94 ans = 60
n = 95 ans = 62
n = 96 ans = 64
n = 97 ans = 66
n = 98 ans = 68
n = 99 ans = 70
n = 100 ans = 72
首先发现有重复,于是把所有的ans 第一次出现的 n 和 ans 单独列出来。
n = 1 ans = 1
n = 2, ans = 2
n = 7 ans = 6
n = 8, ans = 8;
n = 13, ans = 10;
n = 14, ans = 12;
n = 15, ans = 14;
n = 16 ans = 16;
n = 25 ans = 18
n = 26 ans = 20
n = 27 ans = 22
n = 28 ans = 24
n = 29 ans = 26
n = 30 ans = 28
n = 31 ans = 30
n = 32 ans = 32
于是规律便得出来了, 2 ^ (i -1) < n <= 2^(i) , 那么 ans 便为 (n - 2 ^ (i-1)) * 2;
#include <cstdio>
#include <algorithm>
using namespace std;
int a[21];
int main(){
int n;
a[0] = 1;
for (int i = 1; i <= 20; i++)a[i] = 2 * a[i - 1];
while (scanf("%d", &n) == 1 && n){
if (n == 1)puts("1");
else {
for (int i = 0; i < 20; i++){
if (n > a[i] && n <= a[i+1]){
printf("%d\n", 2*(n - a[i]));
break;
}
}
}
}
return 0;
}