首页 > 其他分享 >leetcode-1009-easy

leetcode-1009-easy

时间:2023-03-29 20:57:59浏览次数:35  
标签:10 easy binary int complement stack 1009 integer leetcode

Complement of Base 10 Integer

The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.

For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer n, return its complement.

Example 1:

Input: n = 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:

Input: n = 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:

Input: n = 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Constraints:

0 <= n < 109
Note: This question is the same as 476: https://leetcode.com/problems/number-complement/

思路一:先用辗转相除法转换进制,使用队列存储值,最后还原数字

    public int bitwiseComplement(int n) {
        if (n == 0) return 1;
        Deque<Integer> stack = new ArrayDeque<>();

        while (n > 0) {
            int x = n % 2;
            stack.push(x == 0 ? 1 : 0);
            n /= 2;
        }

        int result = 0;
        int p = 1;
        while (!stack.isEmpty()) {
            result += stack.pollLast() * p;
            p *= 2;
        }

        return result;
    }

标签:10,easy,binary,int,complement,stack,1009,integer,leetcode
From: https://www.cnblogs.com/iyiluo/p/17270265.html

相关文章

  • 【LeetCode】35.搜索插入位置
    题目描述  解法思路:二分查找classSolution{public:intsearchInsert(vector<int>&nums,inttarget){intleft=0,right=nums.size()-1......
  • 【LeetCode】278.第一个错误的版本
    题目描述  解法思路:二分查找注意:当第一个 isBadVersion(mid)的结果为true时,得到第一个错误的版本//TheAPIisBadVersionisdefinedforyou.//boolisBadVe......
  • leetcode 176
    leetcode176第二高的薪水,查第二高的人的信息1、使用ifnull(exp1,exp2)函数,limitoffset子句 selectifnull((selectdistinctsalaryfromEmployeeorderb......
  • CF1009F 题解
    一、题目描述:给定一棵以 1 为根,n 个节点的树。设 d(u,x) 为 u的子树中到 u 距离为 x 的节点数。对于每个点,求一个最小的 k,使得 d(u,k) 最大。 二、......
  • LeetCode 101.对称二叉树
    1.题目:给你一个二叉树的根节点 root ,检查它是否轴对称。 示例1:输入:root=[1,2,2,3,4,4,3]输出:true2.代码:方法一:递归实现/***Definitionforabinarytreenode.......
  • #yyds干货盘点# LeetCode程序员面试金典:盛最多水的容器
    题目:给定一个长度为n的整数数组 height 。有 n 条垂线,第i条线的两个端点是 (i,0) 和 (i,height[i]) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以......
  • #yyds干货盘点# LeetCode面试题:不同路径
    1.简述:一个机器人位于一个mxn 网格的左上角(起始点在下图中标记为“Start”)。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Fin......
  • Leetcode81. 搜索旋转排序数组 II
    classSolution{public:boolcheck(vector<int>&nums,inttarget,intl,intr)//[l,r]区间查找target{while(l<r){intmid=(......
  • 3月更新!EasyOps®全平台超10项功能升级,您的需求在其中~
    又到了每月产品盘点时刻,12大新功能上线和升级优化,涉及Hyperlnsight超融合持续观测平台、DevOps持续交付平台、AutoOps自动化运维平台、ITSM服务平台,在不断的技术创新过程中,......
  • 【单调队列】LeetCode 239. 滑动窗口最大值
    题目链接239.滑动窗口最大值思路单调队列的使用方法,可以参考【单调队列】LeetCode面试题59-II.队列的最大值在本题中将滑动窗口的移动看作往队列中放数和取数的过......