Home >Backend Development >Python Tutorial >Python计算回文数的方法

Python计算回文数的方法

WBOY
WBOYOriginal
2016-06-06 11:21:442437browse

本文实例讲述了Python计算回文数的方法。分享给大家供大家参考。具体如下:

这里检查数字是不是回文数,用196算法生成一个数字的回文数

num = 905;
def is_Palindrome(num):
  """
  判断一个数字是不是回文数,这里有些取巧了
  :param num:
  :return:
  """
  """
  :param num:
  :return:
  """
  temp = "%d"%num;
  str = temp[::-1];
  if temp == str:
    return True;
  else:
    return False;
def create_Palindrome(num):
  """
  用196算法计算指定数字的回文数
  :param num:
  :return:
  """
  count = 0;
  while True:
    if True == is_Palindrome(num):
      output = "这是一个回文数:%d"%num + "\r\n总共次数为%d"%count;
      print(output);
      break;
    else:
      num = add(num);
      count += 1;
def add(num):
  """
  num 与自己倒序的数字相加
  :param num:
  :return:
  """
  temp = "%d"%num;
  str = temp[::-1];
  return int(temp) + int(str);
print(create_Palindrome(num));

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn