如何将字符串操作为整数以及如何使用按位运算符..此函数已在c中用于从数字字符串中获取输入
"gc and ll are defined like this.. typedef long long LL;
#define gc getchar_unlocked()"
inline LL inp()
{
LL num = 0;
char p = gc;
while(p<33)p=gc;
while(p>33) {
num = (num << 3)+ (num << 1)+ (p -'0');
p = gc;
}
return num;
};
答案 0 :(得分:2)
我认为char p = gc
从input
获得了一个角色。
while(p<33)p=gc;
只是输入输入,直到输入空格以外的其他内容? (空格是十进制字符32。)
然后,虽然输入不是空格,
(num << 3) + (num << 1)
相当于num * 10
(num << 3
相当于num * 8
,num << 1
相当于num * 2
,num * 8 + num * 2
可以写成num * (8+2)
,简化为num * 10
)。
p - '0'
将输入字符(例如'9'[char 57])转换为相应的整数(例如,仅为9)。
如果输入为“123”,则num将等于123,因为:
num = 0;
num = 0 * 10 + 1; (== 1)
num = 1 * 10 + 2; (== 12)
num = 12 * 10 + 3; (== 123)
我希望有所启发。这是非常糟糕的代码,如果输入的数字不是0-9,则行为不正确。
这样写它可能会更好:
// function to read one character from the 'input'
char gc();
// I'm not sure what LL is here, could be long long?
inline LL inp()
{
LL num = 0;
char p = gc();
// keep reading characters until a number is encountered
while((p < '0') || (p > '9'))
{
p = gc();
}
// loop until a non-number is encountered
while((p >= '0') && (p <= '9'))
{
// Shift the previously read digits up by one 'tens' column
num *= 10;
// Add in the newly read digit
num += p -'0';
// Read the next character
p = gc();
}
return num;
}