返回

旋转数字 —— 两次旋转也能成正数

后端

旋转数字,顾名思义,就是旋转后仍然是正整数的数字。这种数学游戏在开发面试中经常出现,考验的是程序员的算法能力和数学直觉。

旋转数字的基本原理

旋转数字的基本原理很简单:一个数字旋转后仍然是正整数,当且仅当这个数字的每一位都是旋转数字。例如,数字 123 是旋转数字,因为旋转后得到 321,也是一个正整数。而数字 124 不是旋转数字,因为旋转后得到 421,其中 4 不是旋转数字。

旋转数字的判定方法

根据旋转数字的基本原理,我们可以很容易地判定一个数字是否旋转数字。一种方法是将数字每一位拆分成单独的数字,然后检查每个数字是否旋转数字。另一种方法是使用数学运算。

Python 代码实现

def is_rotated_number(num):
  """
  判断一个数字是否旋转数字。

  Args:
    num: 要判断的数字。

  Returns:
    True 如果 num 是旋转数字,否则 False。
  """

  # 将数字拆分成单独的数字。
  digits = []
  while num > 0:
    digit = num % 10
    digits.append(digit)
    num //= 10

  # 检查每个数字是否旋转数字。
  for digit in digits:
    if digit not in [0, 1, 6, 8, 9]:
      return False

  # 如果所有数字都是旋转数字,则返回 True。
  return True


# 测试代码。
print(is_rotated_number(123))  # True
print(is_rotated_number(124))  # False
print(is_rotated_number(101))  # True
print(is_rotated_number(111))  # True

Java 代码实现

import java.util.Arrays;

public class RotatedNumber {

  public static boolean isRotatedNumber(int num) {
    // 将数字拆分成单独的数字。
    int[] digits = new int[10];
    while (num > 0) {
      int digit = num % 10;
      digits[digit]++;
      num /= 10;
    }

    // 检查每个数字是否旋转数字。
    int[] rotatedDigits = {0, 1, 6, 8, 9};
    for (int digit : digits) {
      if (Arrays.binarySearch(rotatedDigits, digit) < 0) {
        return false;
      }
    }

    // 如果所有数字都是旋转数字,则返回 True。
    return true;
  }

  // 测试代码。
  public static void main(String[] args) {
    System.out.println(isRotatedNumber(123)); // True
    System.out.println(isRotatedNumber(124)); // False
    System.out.println(isRotatedNumber(101)); // True
    System.out.println(isRotatedNumber(111)); // True
  }
}

C++ 代码实现

#include <iostream>
#include <vector>

using namespace std;

bool isRotatedNumber(int num) {
  // 将数字拆分成单独的数字。
  vector<int> digits;
  while (num > 0) {
    int digit = num % 10;
    digits.push_back(digit);
    num /= 10;
  }

  // 检查每个数字是否旋转数字。
  vector<int> rotatedDigits = {0, 1, 6, 8, 9};
  for (int digit : digits) {
    if (find(rotatedDigits.begin(), rotatedDigits.end(), digit) == rotatedDigits.end()) {
      return false;
    }
  }

  // 如果所有数字都是旋转数字,则返回 True。
  return true;
}

// 测试代码。
int main() {
  cout << isRotatedNumber(123) << endl; // True
  cout << isRotatedNumber(124) << endl; // False
  cout << isRotatedNumber(101) << endl; // True
  cout << isRotatedNumber(111) << endl; // True

  return 0;
}

JavaScript 代码实现

function isRotatedNumber(num) {
  // 将数字拆分成单独的数字。
  const digits = num.toString().split('');

  // 检查每个数字是否旋转数字。
  const rotatedDigits = ['0', '1', '6', '8', '9'];
  for (const digit of digits) {
    if (!rotatedDigits.includes(digit)) {
      return false;
    }
  }

  // 如果所有数字都是旋转数字,则返回 True。
  return true;
}

// 测试代码。
console.log(isRotatedNumber(123)); // true
console.log(isRotatedNumber(124)); // false
console.log(isRotatedNumber(101)); // true
console.log(isRotatedNumber(111)); // true

希望这篇题解对您有所帮助。如果您有其他问题,请随时留言。