Press "Enter" to skip to content

月度归档: 2022 年 6 月

9. 回文数

方法一:

反转一半数字:例如输入1331,我们可以将数字“1331”的后半部分从“31”反转成“13”在和前半部分进行比较,如果二者相同我们就得知数字“1331”是回文数

C 代码解法

#include<stdbool.h>

bool isPalindrome(int x){
    // 特殊情况处理:如果 x 是负数或者末尾是 0 的非零数,则不可能是回文数
    if (x < 0 || (x != 0 && x % 10 == 0)){
        return false;
    }

    long reversed_num = 0;
    int original_x = x;

    //反转 x 的一半
    while (x > 0){
        int digit = x % 10;
        reversed_num = reversed_num * 10 + digit;
        x /= 10;
    }

    // 如果原始数字长度是奇数,去掉最后一位
    if (original_x == reversed_num || original_x == reversed_num / 10){
        return true;
    } else {
        return false;
    }
}

Python3 代码解法

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x = str(x)
        if x == x[::-1]:
            return True
        else:
            return False

Source: LeetCode(The title reproduced in this blog is for personal study use only)

Zen of Python

The Zen of Python is a collection of 19 “guiding principles” for writing computer programs that influence the design of the Python programming language. Software engineer Tim Peters wrote this set of principles and posted it on the Python mailing list in 1999. Peters’s list left open a 20th principle “for Guido to fill in”, referring to Guido van Rossum, the original author of the Python language. The vacancy for a 20th principle has not been filled.

Peters’s Zen of Python was included as entry number 20 in the language’s official Python Enhancement Proposals and was released into the public domain. It is also included as an Easter egg in the Python interpreter, where it can be displayed by entering import this.

Principles

The principles are listed as follows:

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren’t special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one– and preferably only one –obvious way to do it.
  • Although that way may not be obvious at first unless you’re Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it’s a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea – let’s do more of those!