剑指Offer(面试题49-50)

面试题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》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值