给定一个整数 N,我们的任务是打印前 N 个纯数字。如果一个数字满足以下条件,则称其为纯数字:
- 它的位数是偶数。
- 所有的位数字只能是 4 或 5。
- 并且这个数字是一个回文数。
前几个纯数字是 44, 55, 4444, 4554, 5445, 5555, … 示例:
> 输入: N = 4
> 输出: 44 55 4444 5445
>
>
>
>
>
> 输入: N = 10
> 输出: 44 55 4444 4554 5445 5555 444444 454454 544445 554455
方法: 这个思路与这里讨论的方法类似。在队列的每一步中,我们都可以通过在上一个数字的两侧(即开头和结尾)分别添加 4 和 5 来生成下一个数字:
q.push("4" + temp + "4");
q.push("5" + temp + "5");
以下是解决此问题的步骤:
- 声明一个向量数据结构和一个队列。
- 实现函数 nPureNumbers(n) 用于生成前 n 个纯数字。
- 将前两个元素 ‘44‘ 和 ‘55‘ 加入队列。
- 当生成的纯数字数量小于 n 时,使用 while 循环生成新的纯数字。
- 从队列中取出第一个元素并将其添加到向量中。
- 现在拼接 ‘4‘ 或 ‘5‘ 来创建两个全新的纯数字,然后将它们加入队列。
- 最后在对生成的纯数字向量进行排序后,打印前 n 个纯数字。
按照这种方式进行,我们可以自然地满足回文数和偶数位长度的要求。下面是上述方法的实现:
CPP14
CODEBLOCK_656f6500
Java
CODEBLOCK_da9c3c70
Python3
CODEBLOCK_98436ab2
C#
“
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
public static void nPureNumbers(int n) {
// Use a queue to store numbers to generate new ones
Queue q = new Queue();
// Use a list to store the generated numbers
List ans = new List();
// Add the initial numbers "44" and "55" to the queue
q.Enqueue("44");
q.Enqueue("55");
int total = 2;
// Generate new numbers until the list has n items
while (ans.Count < n) {
string temp = q.Dequeue();
ans.Add(temp);
// Add new numbers to the queue
q.Enqueue("4" + temp + "4");
q.Enqueue("5" + temp + "5");
}
// Sort the list of numbers by length and then lexicographically
ans.Sort((s, s2) => {
if (s.Length == s2.Length) {
return s.CompareTo(s2);
} else {
return s.Length – s2.Length;
}
});
// Print the list of numbers
foreach (string i in ans) {
Console.Write(i + " ");
}