一、题目描述
题目原文:
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
(给出一个非负整数n,返回一个列表,其元素为从0到n的二进制表示中每一项的1的个数)
题目要求:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
(1、在时间复杂度为O(n)内完成。2、空间复杂度也为O(n)。3、不要用内置方法。)
二、题目分析
思路:
首先,我们需要知道负数是没有回文数一说的。
其次,根据提示,思路1:将整形数字转化为字符串来制作。因为回文数是关于中间位置对称的,转化后根据数组下标,来进行首尾
判等操作即可(根据奇偶分为两种情况,奇数的中位数不用进行判断,且每种情况中,要判等的首位两个
数下标和为串长lenth - 1)。
思路2:将整形数字反转后与原数字判等即可,Reverse Integer题目链接如下:
http://blog.csdn.net/u014615155/article/details/53258668。
我选择的是思路1,因为要考虑到不用额外空间的问题,我觉得类型转化过程中可能会有空间的浮动变化,但应该没有思路2直接开辟
新空间对空间的需求 那么多。
三、Python代码
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ #我们要知道负数不是回文数 if x < 0: return False #转化为字符串,用下标来判断 x = str(x) lenth = len(x) #用&操作来判定是奇数还是偶数,注意下标的匹配问题(每一对收尾判断相同的两个数的下标和恰为lenth-1)。 if lenth & 1 == 0: for i in range(0, lenth / 2): if x[i] != x[lenth - i - 1]: return False else: for i in range(0, (lenth + 1) / 2): if x[i] != x[lenth - i - 1]: return False return True
四、其他
题目链接:https://leetcode.com/problems/palindrome-number/
Runtime: 221 ms
想法不够优化,欢迎大家留言交流~