From 4c891c122436dc309d0ad5e5a8cace2678249710 Mon Sep 17 00:00:00 2001 From: haiker2011 Date: Mon, 8 Oct 2018 19:38:57 +0800 Subject: [PATCH] add #15 #16 python implement --- notes/面试总结.md | 121 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) diff --git a/notes/面试总结.md b/notes/面试总结.md index 96728367..7f98eff2 100644 --- a/notes/面试总结.md +++ b/notes/面试总结.md @@ -16,6 +16,8 @@ * [12. 矩阵中的路径](#12-矩阵中的路径) * [13. 机器人的运动范围](#13-机器人的运动范围) * [14. 剪绳子](#14-剪绳子) +* [15. 二进制中 1 的个数](#15-二进制中-1-的个数) +* [16. 数值的整数次方](#16-数值的整数次方) * [参考文献](#参考文献) @@ -1117,6 +1119,125 @@ def integerBreak(n): timesOf2 = (n - timesOf3 * 3) // 2 return pow(3, timesOf3) * pow(2, timesOf2) ``` +# 15. 二进制中 1 的个数 + +[NowCoder](https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&tqId=11164&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) + +## 题目描述 + +输入一个整数,输出该数二进制表示中 1 的个数。 + +### n&(n-1) + +该位运算去除 n 的位级表示中最低的那一位。 + +``` +n : 10110100 +n-1 : 10110011 +n&(n-1) : 10110000 +``` + +时间复杂度:O(M),其中 M 表示 1 的个数。 + + +```java +public int NumberOf1(int n) { + int cnt = 0; + while (n != 0) { + cnt++; + n &= (n - 1); + } + return cnt; +} +``` + + +### Integer.bitCount() + +```java +public int NumberOf1(int n) { + return Integer.bitCount(n); +} +``` + +```python +# -*- coding:utf-8 -*- +class Solution: + def NumberOf1(self, n): + # write code here + if n<0: + n=n&0xFFFFFFFF #把负号去掉,如果负号在后面会陷入死循环 + return bin(n).count('1') +``` + +```python +# -*- coding:utf-8 -*- +class Solution: + def NumberOf1(self, n): + # write code here + return sum([(n>>i & 1) for i in range(0,32)]) +``` + +# 16. 数值的整数次方 + +[NowCoder](https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) + +## 题目描述 + +给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent,求 base 的 exponent 次方。 + +## 解题思路 + +下面的讨论中 x 代表 base,n 代表 exponent。 + +

+ +因为 (x\*x)n/2 可以通过递归求解,并且每次递归 n 都减小一半,因此整个算法的时间复杂度为 O(logN)。 + +```java +public double Power(double base, int exponent) { + if (exponent == 0) + return 1; + if (exponent == 1) + return base; + boolean isNegative = false; + if (exponent < 0) { + exponent = -exponent; + isNegative = true; + } + double pow = Power(base * base, exponent / 2); + if (exponent % 2 != 0) + pow = pow * base; + return isNegative ? 1 / pow : pow; +} +``` +```python +# -*- coding:utf-8 -*- +class Solution: + def Power(self, base, exponent): + # write code here + flag = 0 + if base == 0: + return False + if exponent == 0: + return 1 + if exponent < 0: + flag = 1 + result = 1 + for i in range(abs(exponent)): + result *= base + if flag == 1: + result = 1 / result + return result +``` + +```python +# -*- coding:utf-8 -*- +class Solution: + def Power(self, base, exponent): + # write code here + return pow(base, exponent) +``` # 参考文献