Reverse Bits 及format()总结

来源:互联网 发布:淘宝卖家版电脑版 编辑:程序博客网 时间:2024/06/07 20:21

题目详情:https://leetcode.com/problems/reverse-bits/description/

自己写的代码:

class Solution:    # @param n, an integer    # @return an integer    def reverseBits(self, n):        ns=bin(n)[2:] #转换为二进制,转换后二进制的前两位为‘0b’,所以从第三位取        #print len(ns),"  ",ns        while len(ns)<32: #如果不足32位            ns='0'+ns#则进行添0处理        #print len(ns),"  ",ns        #print int(ns[::-1],2)        return int(ns[::-1],2)#进行逆置处理,并把逆置后的二进制字符串转换为十进制                              #第二个参数代表原数是多少进制表示的

看见别人写的代码,学习了一下

class Solution:    # @param n, an integer    # @return an integer    def reverseBits(self, n):        n="{0:032b}".format(n)        return int(n[::-1],2)

通过参考python官网和博客,进行总结如下:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]fill        ::=  <any character>align       ::=  "<" | ">" | "=" | "^"sign        ::=  "+" | "-" | " "width       ::=  integerprecision   ::=  integertype        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

fill: 可以是任意的字符。当输出的宽度小于指定的宽度时,用fill指定的字符来填充
align:指定对齐方式。”<”:左对齐;”>”:右对齐; “^”:居中对齐;”+”:没看懂什么意思
sign:设置数字符号的显示。”+”:正数显示”+”,负数显示”-“;”-“:负数显示”-“,正数不显示符号;” “:正数显示” “,即空格,负数显示”-“

>>> "{:@<+b}".format(8)'+1000'>>> "{:@<+b}".format(-8)'-1000'>>> "{:@<-b}".format(-8)'-1000'>>> "{:@<-b}".format(8)'1000'>>> "{:@< b}".format(8)' 1000'>>> "{:@< b}".format(-8)'-1000'

“#”:显示数字的进制,只针对数字。
(The ‘#’ option is only valid for integers, and only for binary, octal, or hexadecimal output. If present, it specifies that the output will be prefixed by ‘0b’, ‘0o’, or ‘0x’, respectively.)
“0”:当fill没有指定的时候,如果有该位”0”,则表示由”0”补位

>>> "{:@<+#032b}".format(8)'+0b1000@@@@@@@@@@@@@@@@@@@@@@@@@'>>> "{:<+#032b}".format(8)'+0b10000000000000000000000000000'>>> "{:<+#32b}".format(8)'+0b1000                         '

其实我也没太懂,英文文档的说明。
“,”:表示是否用”,”分割大数

>>> "{:,}".format(1000000000)'1,000,000,000'

width:设定数字的宽度,如果没有指定则由数字的实际宽度决定。
(width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content)
type:表示要转换到的
“.precision”:设置小数点后面显示多少位

>>> "{:.4}".format(123.45678)'123.5'

“type”:设置呈现的方式。

python的英文文档地址https://docs.python.org/2/library/string.html#formatspec

另外注意:
1、”{0:032b}”中的第一个”0”,代表第一个参数;1表示第二个参数,以此类推

>>> "{0} {1}".format("hello","world")'hello world'>>> "{1} {0}".format("hello","world")'world hello'>>> "{1} {1}".format("hello","world")'world world'>>> 

2 “:”指定代表元素需要的操作。

本人英语水平有限,若有什么错误,欢迎指正!

原创粉丝点击