leetCode191/201/202/136 -Number of 1 Bits/Bitwise AND of Numbers Range/Happy Number/Single Number「建议收藏」

leetCode191/201/202/136 -Number of 1 Bits/Bitwise AND of Numbers Range/Happy Number/Single Number

大家好,又见面了,我是全栈君。

一:Number of 1 Bits

题目:

Write a function that takes an unsigned integer and returns the number of ’1′ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11′ has binary representation 00000000000000000000000000001011, so the function should return 3.

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

解法一:

此题关键是怎样推断一个数字的第i为是否为0  即: x& (1<<i)

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        for(int i = 0; i < 32; i++){
            if((n & (1<<i)) != 0)count++;
        }
        return count;
        
    }
};

解法二:此解关键在于明确n&(n-1)会n最后一位1消除,这样循环下去就能够求出n的位数中为1的个数

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while(n > 0){
            n &= n-1;
            count ++;
        }
        return count;
    }
};

二:
Bitwise AND of Numbers Range

题目:

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

分析:此题提供两种解法:1:当m到n之前假设跨过了1,2,4,8等2^i次方的数字时(即推断m与n是否具有同样的最高位),则会为0,否则顺序将m到n相与。

解法二:利用上题中的思路。n&(n-1)会消除n中最后一个1,如1100000100当与n-1按位与时便会消除最后一个1,赋值给n(这样就减免了非常多不必要按位与的过程)

解法一:

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int bitm = 0, bitn = 0;
        for(int i =0; i < 31; i++){
            if(m & (1<<i))bitm = i;
            if(n & (1<<i))bitn = i;
        }
        if(bitm == bitn){
            int sum = m;
            for(int i = m; i < n; i++)  // 为了防止 2147483647+1 超过范围
                sum = (sum & i);
            sum = (sum & n);
            return sum;
        }
        else return 0;
    }
};

解法二:

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        while(n > m){
            n &= n-1;
        }
        return n;
    }
};

三:
Happy Number

题目:

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

分析:此题关键是用一个set或者map来存储该数字是否已经出现过————hash_map+math

class Solution {
public:
    bool isHappy(int n) {
        while(n != 1){
            if(hset.count(n)) return false;    // 通过hashtable 推断是否出现过
            hset.insert(n);
            int sum = 0;
            while(n != 0){    // 求元素的各个位置平方和
                int mod = n%10;
                n = n/10;
                sum += mod * mod;
            }
            n = sum;
        }
        return true;
        
    }
private:
    set<int> hset;
};

四:Single Number

题目:

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

分析:此题关键在于用到异或

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for(int i = 0; i < nums.size(); i++)
            ans ^= nums[i];
        return ans;
        
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115212.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 字节跳动视频编解码面经「建议收藏」

    字节跳动视频编解码面经「建议收藏」三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时想着能进去就不错了,管他哪个岗呢,就同意了面试…

    2022年7月13日
    36
  • 怎么开外汇平台_如何搭建一个外汇平台

    怎么开外汇平台_如何搭建一个外汇平台外汇市场从世纪之初进入中国,到如今有十几个年头。从起初耳熟能详的几个平台商到现在如雨后春笋般出现,中国的外汇市场越来越开放,价格成本也越来越透明。很多外汇代理商不断发展壮大,对搭建自己的平台有了需求。开外汇平台赚钱,是一个普遍流传的说法。但是开平台到底有怎么样的风险,需要注意哪些环节,要办理哪些手续,多数人还是感到非常神秘。汇商琅琊榜小编今天结合平台搭建行业资深人士的经验,来和大家谈谈怎么样搭建…

    2022年9月11日
    3
  • JSPJavaBean组件(动作标签)[通俗易懂]

    JSPJavaBean组件(动作标签)[通俗易懂]什么是JavaBean组件JavaBeans组件是具有以下功能的Java类:一个无参构造函数。(Ano-argumentconstructor.)定义属性的访问器和修改器(getter和setter方法)(Propertiesdefinedwithaccessorsandmutators(getterandsettermethod).)类不得定义任何公共实例变量。该类必须实现java.io.Serializable接口。javaBean的意义javaBean作为数据

    2022年7月27日
    11
  • 面试官:请你谈谈Java的类加载过程[通俗易懂]

    面试官:请你谈谈Java的类加载过程[通俗易懂]刚刚走出校门的应届毕业生,如果在去寻求一份Java开发的工作时,你的面试官很有可能一边看着你的简历,一边漫不经心地问你:了解过Java类的加载过程吗?这个时候你一定要注意了,虽然这是一个老生常谈的问题,但是这也是一个非常能够考验你Java功底的问题。如果你答好了,这是你应该的;如果你没答好,那么对不起,面试官心中已经给了你不及格。今天,小编就Java类加载过程这个问题,抛砖引玉,说一下…

    2022年8月11日
    6
  • 奇怪的现象:touchesBegan: 与UITapGestureRecognizer手势没有人响应 以及set方法的妙用

    奇怪的现象:touchesBegan: 与UITapGestureRecognizer手势没有人响应 以及set方法的妙用本打算实现一个点击按钮弹出一个landKindView然后点击屏幕其他部分时移除这个VIew,没想到的是,出了诸多不可思议的问题。在给这个控制器的View添加手势时,然后居然拦截不到,touchesbegin方法,然后又试了下添加tapGesture,依旧是没有反应。然后我试着在touchesBegin方法中 实现[supertouchesBegins….];依旧是没有任

    2022年7月25日
    10
  • NP-Hard问题浅谈

    NP-Hard问题浅谈看相关算法的paper的时候,经常会出现NP-Hard这个词。本博主也不是纯数学系出身,对于这么高深的问题自然没有特别深入独到的理解。但是本博主的习惯就是看到一个东西老在眼前晃来晃去但自己还不是很明白,就有强迫症一定要搞明白这到底是个什么玩意。so,咱们就来看看这个NP-Hard问题,怎么用最简单的方式去了解。1.世界七大数学难题之首2000年,美国克莱数学研究所公布了世界七大数学难题,又称千禧年大

    2022年9月13日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号