leetcode Number Complement

476. Number Complement

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

import java.util.*;

public class Solution {
public static int findComplement(int num) {
   int comp = 0;
   int i = 0;
        while(num != 0){
            int a = num % 2;
            int b = num / 2;
            num = b;
            comp += ((a+1)%2)*Math.pow(2, i);
            i++;
        }
        return comp;
}
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
try{
int num = reader.nextInt();
if(num>=0){
System.out.print(findComplement(num));
}
}catch(Exception e){
System.out.print("wrong");
}

}
}
### LeetCode Easy Problems LeetCode 提供了大量的简单难度(Easy)编程题目,这些题目适合初学者练习基础算法和数据结构的知识。以下是几个常见的 LeetCode Easy 题目及其简要说明: #### 1. 两数之和 (Two Sum) 给定一个整数数组 `nums` 和一个目标值 `target`,请你在该数组中找出和为目标值的两个整数,并返回它们的数组下标[^1]。 ```python def twoSum(nums, target): hashmap = {} for i, num in enumerate(nums): complement = target - num if complement in hashmap: return [hashmap[complement], i] hashmap[num] = i ``` #### 2. 整数反转 (Reverse Integer) 给出一个 32 位有符号整数,你需要将这个整数中每位上的数字进行反转[^2]。 ```python def reverse(x): sign = -1 if x < 0 else 1 x_abs = abs(x) reversed_x = int(str(x_abs)[::-1]) result = sign * reversed_x if result < -2**31 or result > 2**31 - 1: return 0 return result ``` #### 3. 回文数 (Palindrome Number) 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数[^3]。 ```python def isPalindrome(x): if x < 0: return False return str(x) == str(x)[::-1] ``` #### 4. 合并两个有序链表 (Merge Two Sorted Lists) 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的[^5]。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(l1, l2): dummy = ListNode() current = dummy while l1 and l2: if l1.val < l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next current.next = l1 or l2 return dummy.next ``` #### 5. 移除元素 (Remove Element) 给你一个数组 `nums` 和一个值 `val`,原地移除所有数值等于 `val` 的元素,并返回移除后数组的新长度[^5]。 ```python def removeElement(nums, val): k = 0 for i in range(len(nums)): if nums[i] != val: nums[k] = nums[i] k += 1 return k ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值