打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
LeetCode之Number Complement

1、题目

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.

2、代码实现

public class Solution {
    public int findComplement(int num) {
    if (num <= 0)
    return 0;
    String result = "";
    while (num > 0) {
    result += num % 2;
    num = num / 2;
    }
    int length = result.length();
    int lastResult = 0;
    for (int i = 0; i < length - 1; ++i) {
    if (result.charAt(i) == '0') {
    int temp = (int) Math.pow(2, i);
    lastResult += temp;
    }
    }
    return lastResult;
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
512,反转二进制位
1290. Convert Binary Number in a Linked List to Integer (E)
Fundamental types
【源码】【wav音频解析】之wavread的C 实现
DICOM的常用Tag分类和说明
OracleUTL_RAW
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服