Problem Statement
A lucky number is a positive integer consisting of only the digits 4 and 7.
Given an int a, return an int b strictly greater than a, such that a XOR b is a lucky number. (See Notes for the definition of XOR.) The number b should be in the range 1 to 100, inclusive. If such a number does not exist, return -1. If there are multiple such b, you may return any of them.
Definition
Class:
LuckyXor
Method:
construct
Parameters:
int
Returns:
int
Method signature:
int construct(int a)
(be sure your method is public)
Limits
Time limit (s):
2.000
Memory limit (MB):
256
Stack limit (MB):
256
Notes
XOR is the bitwise exclusive-or operation. To compute the value of P XOR Q, we first write P and Q in binary. Then, each bit of the result is computed by applying XOR to the corresponding bits of the two numbers, using the rules 0 XOR 0 = 0, 0 XOR 1 = 1, 1 XOR 0 = 1, and 1 XOR 1 = 0.
For example, let’s compute 21 XOR 6. In binary these two numbers are 10101 and 00110, hence their XOR is 10011 in binary, which is 19 in decimal.
You can read more about the XOR operation here: https://en.wikipedia.org/wiki/Exclusive_or
Constraints
a is between 1 and 100, inclusive.
Examples
0)
4
Returns: 40
4 XOR 40 = 44, 44 is a lucky number.
1)
19
Returns: 20
19 XOR 20 = 7
2)
88
Returns: 92
88 XOR 92 = 4
3)
36
Returns: -1
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
题意
只包含4和7的数字是幸运数字,现在给一个数字 a(0≤a≤100) ,要求返回一个整数 b(a<b≤100) 使得 a⊕b 为一个幸运数字
题解
a,b
都小于一百,转换成二进制最多为7位
0⊕0=0
,所以
a⊕b
转换成二进制最多有7位,二进制七位以下的幸运数字有
4,7,44,47,74,77
,没了。。然后如果
a⊕b=c
那么
b⊕c=a
,为啥呢。。因为
0⊕0=0,1⊕1=0,1⊕0=1,0⊕1=1
。。没了。。然后用上面的六个幸运数组异或枚举就好,能够造出大于
a
的就输出,不能就返回
代码
class LuckyXor {
public:
int construct(int);
};
int LuckyXor::construct(int a) {
int s[]={4,7,44,47,74,77};
int t;
for(int i=0;i<6;i++)
{
t=a^s[i];
if(t<=100&&t>=1&&t>a)
return a^s[i];
}
return -1;
}