/*读取字符的缓存*/ char ch_buffer; /*符号*/ bool signum; inlinevoidread(int& l){ l = 0; /*跳过非数字部分*/ do ch_buffer = getchar(); while ((ch_buffer < '0' || ch_buffer > '9') && ch_buffer != '0' && ch_buffer != '-'); /*判断是否为负*/ if (ch_buffer == '-') ch_buffer = getchar(), signum = true; /*关键的读取,使用位运算,(l<<3)+(l<<1)等价于l * 10 请不要在 O2 下使用, *但速度更快,尤其是对于数据大的情况*/ while (ch_buffer <= '9' && ch_buffer >= '0') l = (l << 3) + (l << 1) + ch_buffer - '0', ch_buffer = getchar(); if (signum) l = -l, signum = false; }
1 2 3 4 5 6 7 8 9
/*这样也可以*/ inlinevoidread(int& x){ x = 0; char c; for (c = getchar(); c < '0' || c > '9'; c = getchar()) ; for (; c >= '0' && c <= '9'; c = getchar()) x = (x << 3) + (x << 1) + c - '0'; }