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)
上一篇 2022年2月7日 下午4:00
下一篇 2022年2月7日 下午4:00


相关推荐

  • Java 工厂模式

    Java 工厂模式简单工厂模式详解简单工厂模式用来定义一个工厂类,它可以根据参数的不同返回不同类的实例,被创建的实例通常都具有共同的父类。因为在简单工厂模式中用于创建实例的方法是静态方法,因此简单工厂模式又被称为静态工厂方法模式,它属于类创建型模式。简单工厂模式的要点在于,当我们需要什么,只需要传入一个正确的参数,就可以获取我们所需要的对象,而无需知道其创建细节。简单工厂模式结构比较简单,其核心是工厂类的设计,其机构如图所示:在简单工厂模式结构图中包含如下几个角色。Factory(工厂角色):工厂角色即工厂类,它

    2022年7月20日
    24
  • 【OpenCV3】直线拟合–FitLine()函数详解

    【OpenCV3】直线拟合–FitLine()函数详解一 FitLine 函数原型 CV EXPORTS WvoidfitLine InputArraypo 待输入点集 一般为二维数组或 vector 点集 OutputArrayl 输出点集 一个是方向向量 另一个是拟合直线上的点 Vec4f 2d 或 Vec6f 3d 的 vector intdistType

    2026年3月16日
    1
  • 为什么Qwen3系列模型中没有720亿参数规模的Qwen3-72B?Qwen3-72B还会发布吗?NO!

    为什么Qwen3系列模型中没有720亿参数规模的Qwen3-72B?Qwen3-72B还会发布吗?NO!

    2026年3月13日
    2
  • 虚拟IP简介「建议收藏」

    虚拟IP简介「建议收藏」什么是虚拟IP虚拟IP(VirtualIPAddress,简称VIP)是一个未分配给真实弹性云服务器网卡的IP地址。弹性云服务器除了拥有私有IP地址外,还可以拥有虚拟IP地址,用户可以通过其中任意一个IP(私有IP/虚拟IP)访问此弹性云服务器。同时,虚拟IP地址拥有私有IP地址同样的网络接入能力,包括VPC内二三层通信、VPC之间对等连接访问,以及弹性公网IP、VPN、云专线等网络接入。多个主备部署的弹性云服务器可以在绑定虚拟IP地址时选择同一个虚拟IP地址。用户可以为该虚拟IP地址绑定一个弹

    2022年10月20日
    3
  • form实现表单提交的各种方法(表单提交源码)

    1、type=”submit”&amp;amp;amp;amp;amp;amp;lt;formname=”form”method=”post”action=”#&amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;lt;inputtype=”submit”name=”submit”value=”提交&amp;amp;amp;amp;amp;quo

    2022年4月18日
    124
  • Lambda表达式超详细总结

    Lambda表达式超详细总结在 2014 年 Oracle 发布了 Java8 在里面增加了 Lambda 模块 于是 Java 程序员们又多了一种新的编程方式 函数式编程

    2026年3月18日
    1

发表回复

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

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