1 Star 0 Fork 332

[]~( ̄ ̄)~* / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README_EN.md 1004 Bytes
一键复制 编辑 原始数据 按行查看 历史
yanglbme 提交于 2020-10-20 11:19 . docs: prettify code

05.07. Exchange

中文文档

Description

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).

Example1:


 Input: num = 2(0b10)

 Output 1 (0b01)

Example2:


 Input: num = 3

 Output: 3

Note:

  1. 0 <= num <= 2^30 - 1
  2. The result integer fits into 32-bit integer.

Solutions

Python3

Java

class Solution {
    public int exchangeBits(int num) {
        int t1 = num >> 1;
    	int t2 = num << 1;
    	return t1 & 0x55555555 | t2 & 0xaaaaaaaa;
    }
}

...

Java
1
https://gitee.com/keshuimao/leetcode.git
git@gitee.com:keshuimao/leetcode.git
keshuimao
leetcode
leetcode
main

搜索帮助