Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Palindrome Number #7

Open
barretlee opened this issue Jul 11, 2017 · 3 comments
Open

Palindrome Number #7

barretlee opened this issue Jul 11, 2017 · 3 comments

Comments

@barretlee
Copy link
Owner

barretlee commented Jul 11, 2017

本题难度:★

不使用额外储存空间,判断一个整数是否为回文数字。例如:

-22 -> false
1221 -> true
1221221 -> true
1234321 -> true
234 -> false

需要注意的是:

  • 考虑负数
  • 不允许使用额外储存空间,比如将数字转换成字符串
  • 反转数字需要考虑溢出问题

参考答案:https://github.com/barretlee/daily-algorithms/blob/master/answers/7.md

@barretlee
Copy link
Owner Author

function resolve(n) {
  if (n < 0) return false;
  var len = 0;
  while(Math.pow(10, len) <= n) len++;
  if (len === 1) return true;
  while(len > 1) {
    if (n % 10 !== ~~(n / Math.pow(10, len - 1))) return false;
    n = ~~ (n % Math.pow(10, len - 1) / 10);
    len -= 2;
  }
  return true;
}

console.assert(resolve(1221) === true, 1);
console.assert(resolve(1221221) === true, 2);
console.assert(resolve(1234321) === true, 3);
console.assert(resolve(234) === false, 4);

@YabZhang
Copy link

YabZhang commented Jul 17, 2017

有一个想法:
首先判断首末两位是否相同,若不同则False;若相同,此时肯定不会溢出,反转后做判断即可;

有一个问题不是很确定,题目要求不能使用额外的存储空间,就这一点我没有想清楚?
不能使用额外的存储空间具体是指什么?
在静态语言,如C中,是不是不能使用额外的堆内存?那Python就不用写了~。~!
如何包括栈空间的变量,那岂不是什么变量都不能用了?

就本题来看,我在代码中将变量n赋值给了一个backup保存,这算不算额外的空间?
如果这个算了?那么length算不算?求解~

@YabZhang
Copy link

def resolve(n):
    # check negative
    if n < 0:
        return False
    
    backup = n
    r_num, length = 0, 1
    while(n // 10 > 0):
        length += 1
        r_num = r_num * 10 + n % 10
        n = n // 10
   
    # single digit
    if length == 1:
        return True
    
    if n != backup % 10:
        return False
    
    r_num = r_num * 10 + n
    if backup == r_num:
        return True
    return False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants