//1-n整数中1出现的次数:时间复杂度nlog(n),因为数字n的位数为O(log n)
int count1OfNumber(int n){
int count = 0;
while (n){
if (n % 10 == 1)
count++;
n /= 10;
}
return count;
}
int NumbersOf1Between1AndN(int n){
if (n < 1){
g_InvalidInput = true;
return 0;
}
int count = 0;
for (int i = 1; i <= n; ++i){
count += count1OfNumber(i);
}
return count;
}
//利用hash表实现快速查找:数组实现的hash表O(1)时间查找,STL map实现的hash表O(log n)时间的查找, map适合数据量不大的情况,内部用二叉查找树实现,按照键排序的;
//定义一个函数:输入两个字符串,从第一个字符串中删除在第二个字符串中出现过的所有字符
void deleteCharInString2(string& string1, string& string2){
if (string1.length() == 0 || string2.length() == 0)
return;
int toBeDeleted[256];
for (int i = 0; i < 256; i++)
toBeDeleted[i] = 0;
for (int i = 0; i < string2.length(); ++i){
toBeDeleted[string2[i]] = 1;
}
for (int i = 0; i < string1.length(); ++i) {
if (toBeDeleted[string1[i]] > 0)
string1.erase(i, 1);
}
}
//把字符串转换成整数:
// 1:考虑特殊输入,空指针,空字符串,只有正负号之后没有数字,字符串中有非数字字符
// 2:考虑整型的(正数)上溢出,(负数)下溢出, 需要把num类型设置为long long才能不溢出,再用num与int的极大极小值比较
// 3:输入测试:正数,负数,0
// 注意!使用全局变量来标记非法输入
enum Status {kValid = 0, kInvalid};
Status g_nStatus = kValid;
int StrToIntCore(char* pStr, bool minus){
long long num = 0;
while (*pStr != '\0'){
if (*pStr >= '0' && *pStr <= '9'){
int flag = minus ? -1 : 1;
int digit = *pStr - '0';
num = num * 10 + digit * flag;
if ((!minus && num > 0x7fffffff) || (minus && num < (signed int)0x80000000)){
num = 0;
break;
}
pStr++;
}
else {
num = 0;
break;
}
}
if (*pStr == '\0'){
g_nStatus = kValid;
}
return (int)num;
}
int StrToInt(char* pStr){
g_nStatus = kInvalid;
long long num = 0;
if (pStr != nullptr || *pStr != '\0'){
bool minus = false;
if (*pStr == '+'){
pStr++;
}
else if (*pStr == '-'){
minus = true;
pStr++;
}
if (*pStr != '\0'){
num = StrToIntCore(pStr, minus);
}
}
return (int)num;
}
// 和为s的数字:排序数组中找出两个和为s的数字
bool FindNumbersWithSum(int data[], int length, int sum, int* num1, int* num2){
bool found = false;
if (data == nullptr || length < 2 || num1 == nullptr || num2 == nullptr){
return found;
}
int ahead = 0;
int behind = length - 1;
*num1 = *num2 = 0;
while (ahead < behind){
long long currentSum = data[ahead] + data[behind];
if (currentSum == sum){
*num1 = data[ahead];
*num2 = data[behind];
found = true;
break;
}
else if (currentSum < sum)
ahead++;
else
behind--;
}
return found;
}
// 左旋转字符串
void Reverse(char* pBegin, char* pEnd){
if (pStr == nullptr || pBegin == nullptr || pEnd == nullptr)
return;
while (pBegin < pEnd){
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
pBegin++; pEnd--;
}
}
char* LeftReverseString(char* pStr, int n){
if (pStr != nullptr){
int nLength = static_cast<int>(strlen(pStr));
if (nLength > 0 && n > 0 && n < nLength){
char* pBegin = pStr;
char* pEnd = pStr + nLength - 1;
Reverse(pStr, pBegin, pEnd);
Reverse(pStr, pBegin, pStr + n - 1);
Reverse(pStr, pStr + n, pEnd);
}
}
return pStr;
}