面试题49:把字符串转换成整数
enum Status {kValid = 0,kInvalid};
int g_nStatus = kValid;
int StrToInt(const char* str)
{
g_nStatus = kInvalid;
long long num = 0;
if(str != NULL && *str != '\0')
{
bool minus =false;
if(*str == '+')
str ++;
else if(*str == '-')
{
str ++;
minus = true;
}
if(*str != '\0')
{
num = StrToIntCore(str,minus);
}
}
return (int)num;
}
long long StrToIntCore(const char* digit,bool minus)
{
long long num=0;
while(*digit != '\0')
{
if(*digit >= '0' &&*digit <= '9')
{
int flag =minus ?-1:1;
num =num * 10 + flag * (*digit - '0');
if((!minus && num > 0x7FFFFFFF)
||(minus && num < (signed int )0x80000000))
{
num = 0;
break;
}
digit ++;
}
else
{
num = 0;
break;
}
}
if(*digit == '\0')
{
g_nStatus = kValid;
}
return num;
}
在上面的代码中,把空字符串“ ”和只有一个正号或者负号的情况都考虑到了。同时正整数的最大值0x7FFF FFFF,最小的负整数是0x8000 0000,因此我们需要分两种情况来分别判断整数是否发生上溢出或者下溢出。
面试题50:书中两个结点的最低公共祖先
bool GetNodePath(TreeNode* pRoot,TreeNode* pNode,list<TreeNode*>&path)
{
if(pRoot == pNode)
return true;
path.push_back(pRoot);
bool found = false;
vector<TreeNode*>::iterator i =pRoot->m_vChildren.begin();
while(!found && i < pRoot->m_vChildren.end())
{
found = GetNodePath(*i,pNode,path);
++i;
}
if(!found)
path.pop_back();
return found;
}
TreeNode* GetLastCommonNode
(
const list<TreeNode*>& path1,
const list<TreeNode*>& path2
)
{
list<TreeNode*>::const_iterator iterator1 = path1.begin();
list<TreeNode*>::const_iterator iterator2 = path2.begin();
TreeNode* pLast = NULL;
while(iterator1 ! =path1.end() && iterator2 != path2.end())
{
if(*iterator1 == *iterator2)
pLast = *iterator1;
iterator1++;
iterator2++;
}
return pLast;
}
TreeNode* GetLastCommonParent(TreeNode* pRoot,TreeNode* pNode1,TreeNode* pNode2)
{
if(pRoot == NULL || pNode1 == NULL || pNode2 == NULL)
return NULL;
list<TreeNode*>path1;
GetNodePath(pRoot,pNode1,path2);
list<TreeNode*> path2;
GetNodePath(pRoot,pNode2,path2);
return GetLastCommonNode(path1,path2);
}
代码中GetNodePath用来得到从根结点pRoot开始到达结点pNode的路径,这条路径保存在path中。函数GetCommonNode用来得到两个路径path1和path2的最后一个公共结点。函数GetLastCommonPath得到path1和path2的最后一个公共结点,即我们要找的最低公共祖先。
参考资料《剑指Offer》