leetcode---Power of Two---lower_bound,upper_bound,binary_search

23 篇文章 2 订阅

Given an integer, write a function to determine if it is a power of two.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

class Solution {
public:
    vector<int> powTwo;

    bool isPowerOfTwo(int n) {
        vector<int> powTwo;    
        int i;
        for(i=0; i<31; i++)
        {
            int a = (1 << i);
            powTwo.push_back(a);
        }
        vector<int>::iterator l, r;
        l = lower_bound(powTwo.begin(), powTwo.end(), n);
        r = upper_bound(powTwo.begin(), powTwo.end(), n);

        if(l == r-1)
            return true;
        else
            return false;
    }
};
class Solution {
public:
    vector<int> powTwo;

    bool isPowerOfTwo(int n) {
        vector<int> powTwo;    
        int i;
        for(i=0; i<31; i++)
        {
            int a = (1 << i);
            powTwo.push_back(a);
        }
        int m = binary_search(powTwo.begin(), powTwo.end(), n);
        if(m == 1)
            return true;
        else
            return false;
    }
};
#include "iostream"
#include "algorithm"
using namespace std;

int main()
{
    int a[] = {2, 7, 7, 7, 11};

    // 正常情况
    int l = lower_bound(a, a+5, 7) - a;
    int u = upper_bound(a, a+5, 7) - a;
    int c = binary_search(a, a+5, 7);
    cout << l << " " << u << " " << c << endl;

    // 找比数组中最小数还小的数
    int l1 = lower_bound(a, a+5, 1) - a;
    int u1 = upper_bound(a, a+5, 1) - a;
    int c1 = binary_search(a, a+5, 1);
    cout << l1 << " " << u1 << " " << c1 << endl;

    // 找比数组中最大数还大的数
    int l2 = lower_bound(a, a+5, 16) - a;
    int u2 = upper_bound(a, a+5, 16) - a;
    int c2 = binary_search(a, a+5, 16);
    cout << l2 << " " << u2 << " " << c2 << endl;

    // 找不超出数组数值范围,但不位于数组中的数字
    int l3 = lower_bound(a, a+5, 8) - a;
    int u3 = upper_bound(a, a+5, 8) - a;
    int c3 = binary_search(a, a+5, 8);
    cout << l3 << " " << u3 << " " << c3 << endl;

    return 0;
}

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值