Number Complement
发布日期:2021-10-22 18:11:22 浏览次数:2 分类:技术文章

本文共 951 字,大约阅读时间需要 3 分钟。

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: 5Output: 2Explanation: 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: 1Output: 0Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0

分析:本题求一个整型数的二进制补数,即对应二进制位取反。

思路:数拆成二进制,同时进行运算,对有效位取反,再组装成十进制数即可。

JAVA CODE

class Solution {    public int findComplement(int num) {
     //将二进制数组(an ... a3 a2 a1 a0)装成十进制。a0+2*(a1+2*(a2+...2*(an+0))) 用递归的思想可以得到很简洁的代码(注意取反操作)。 return (1-num%2)+2*(num==1?0:findComplement(num/2)); }}

 

 

 

 

转载于:https://www.cnblogs.com/baichangfu/p/7421878.html

转载地址:https://blog.csdn.net/weixin_30402343/article/details/94833788 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:iOS:第三方库使用非ARC编译
下一篇:C#基础巩固(2)-Linq To XML创建XML

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月19日 14时54分23秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

Spring篇--01 Spring简介、Spring容器 2019-04-26
Spring篇--02 Spring IOC、注解 2019-04-26
Spring篇--03 Spring MVC之建立第一个spring项目 2019-04-26
【实战】Spring+SpringMVC+Mybatis实现增删改查--(二)SSM分页查询页面搭建(通过URI请求) 2019-04-26
Spring+SpringMVC+Mybatis实现增删改查--(三)SSM分页查询页面搭建(通过json请求) 2019-04-26
架构设计与分层 2019-04-26
【01】Java面试----基础方面的陷阱 2019-04-26
排序算法整合 2019-04-26
Java程序员常见笔试题分析 2019-04-26
Java笔试题 2019-04-26
Spring Boot快速入门---(一)spring boot的创建及几种启动方式 2019-04-26
Spring Boot快速入门---(二)spring boot的项目属性配置及Controller的使用 2019-04-26
Spring Boot快速入门---(三)spring boot的快速连接数据库之spring data jpa以及事务管理 2019-04-26
Spring Boot快速入门---(四)spring boot的表单验证以及AOP处理请求 2019-04-26
【物联网实训项目】------(一)家庭智慧安防系统之前期项目工作准备 2019-04-26
【物联网实训项目】------(二)家庭智慧安防系统之定时监控 2019-04-26
【物联网实训项目】------(三)家庭智慧安防系统之实时监控 2019-04-26
【物联网实训项目】------(四)家庭智慧安防系统之智能温控 2019-04-26
【物联网实训项目】------(五)家庭智慧安防系统之智能监控 2019-04-26
【物联网实训项目】------(六)家庭智慧安防系统之智能监控 2019-04-26