LintCode181将整数A转换为B
来源:互联网 发布:mac版字体下载 编辑:程序博客网 时间:2024/05/22 17:48
原题365描述:
计算在一个 32 位的整数的二进制表式中有多少个 1
.
样例
给定 32
(100000),返回 1
给定 5
(101),返回 2
给定 1023
(111111111),返回 9
挑战
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
标签
原题181描述:
如果要将整数A转换为B,需要改变多少个bit位?
注意事项
Both n and m are 32-bit integers.
样例
如把31转换为14,需要改变2个bit位。
(31)10=(11111)2
(14)10=(01110)2
标签
题目分析:
如两题均为二进制操作,使用python内置函数bin(number)转化为二进制处理
注意题目要求32位二进制表示,需要补0或1。
源码:
1
2
3
4
5
6
7
8
9
10
class
Solution:
# @param num: an integer
# @return: an integer, the number of ones in num
def
countOnes(
self
, num):
# write your code here
twoStr
=
bin
(num).replace(
'0b'
,'')
if
twoStr[
0
]
=
=
'-'
:
return
32
-
twoStr.count(
'0'
)
else
:
return
twoStr.count(
'1'
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class
Solution:
"""
@param a, b: Two integer
return: An integer
"""
def
bitSwapRequired(
self
, a, b):
# write your code here
if
a
=
=
b :
return
0
# 负数补1至32位
if
a <
0
:
strA
=
bin
(a).replace(
'-0b'
,'')
strA
=
(
32
-
len
(strA))
*
'1'
+
strA
else
:
# 整数补0至32位
strA
=
bin
(a).replace(
'0b'
,'')
strA
=
(
32
-
len
(strA))
*
'0'
+
strA
if
b <
0
:
strB
=
bin
(b).replace(
'-0b'
,'')
strB
=
(
32
-
len
(strB))
*
'1'
+
strB
else
:
strB
=
bin
(b).replace(
'0b'
,'')
strB
=
(
32
-
len
(strB))
*
'0'
+
strB
n
=
len
(strA)
count
=
0
for
i
in
range
(
-
1
,
-
n
-
1
,
-
1
):
if
strA[i] !
=
strB[i]:
count
+
=
1
return
count
阅读全文
0 0
- LintCode181将整数A转换为B
- 将整数A转换为整数B
- Lintcode 将整数A转换为B
- 题目:将整数A转换为B
- LintCode 将整数A转换为B
- 将整数A转换为B
- 将整数A转换为B
- lintcode----将整数A转换为B
- 将整数A转换为B
- 将整数A转换为B
- LintCode:将整数A转换为B
- LintCode : 将整数A转换为B
- 将整数A转换为B
- 将整数A转换为B
- lintcode:将整数A转换为B
- 将整数A转换为B-LintCode
- lintcode:将整数A转换为B
- LintCode Flip Bits 将整数A转换为B
- selenium remote出错
- [译] Android ExoPlayer Rtmp HLS DASH SmoothStreaming 其他
- Javascript知识点总结(五)
- 使用qml 创建带不重叠线框Table
- 设置R语言默认工作目录
- LintCode181将整数A转换为B
- 1.6 输出保留12位小数的浮点数
- MySQL中char和varchar的区别
- iptables
- 数据库 MySQL
- Mac 技巧之苹果电脑 Mac OS X 系统下一键即密码锁定屏幕,防止别人乱用乱看的方法
- Java格式化输出之printf
- Session实现一次性验证码(十)
- hadoop 源码编译