元素出栈、入栈顺序的合法性/计算一个整数二进制位中1的个数。

来源:互联网 发布:卫龙工厂淘宝直播视频 编辑:程序博客网 时间:2024/05/22 01:27

元素出栈、入栈顺序的合法性。

如:入栈的序列(1,2,3,4,5),出栈序列为(4,5,3,2,1),则合法。入栈的序列(1,2,3,4,5),出栈序列为(4,5,2,3,1),则不合法。

bool isLegally(const vector<int>& input,const vector<int>& output)    {        stack<int> st;        int i = 0, j = 0;        while (i < input.size())        {            st.push(input[i++]);            while (st.top() == output[j]&&j<output.size())            {                j++;                st.pop();                if (st.empty())                    return true;            }            if (j >= output.size())                return false;        }        return false;    }

计算一个整数二进制位中1的个数。

要求效率尽可能的高。且能正确求正数和负数的二进制中1的个数。

class Solution {public:    /**     * @param num: an integer     * @return: an integer, the number of ones in num     */    int countOnes(int num) {        // write your code here        int count=0;        while(num)        {            ++count;            num&=(num-1);        }        return count;    }};
原创粉丝点击