# 算法题：在只允许两位数字(4和7)的序列中查找第n个元素

2021年3月31日17:43:10 发表评论 633 次浏览

## 本文概述

``````Input : n = 2
Output : 7

Input : n = 3
Output : 44

Input  : n = 5
Output : 74

Input  : n = 6
Output : 77``````

1)如果是奇数, arr [i] = arr [i / 2] * 10 + 4;

2)如果是偶数, arr [i] = arr [(i / 2)-1] * 10 + 7;

## C ++

``````// C++ program to find n-th number in a series
// made of digits 4 and 7
#include <bits/stdc++.h>
using namespace std;

// Return n-th number in series made of 4 and 7
int printNthElement( int n)
{
// create an array of size (n+1)
int arr[n+1];
arr[1] = 4;
arr[2] = 7;

for ( int i=3; i<=n; i++)
{
// If i is odd
if (i%2 != 0)
arr[i] = arr[i/2]*10 + 4;
else
arr[i] = arr[(i/2)-1]*10 + 7;
}
return arr[n];
}

// Driver code
int main()
{
int n = 6;
cout << printNthElement(n);
return 0;
}``````

## Java

``````// Java program to find n-th number in a series
// made of digits 4 and 7

class FindNth
{
// Return n-th number in series made of 4 and 7
static int printNthElement( int n)
{
// create an array of size (n+1)
int arr[] = new int [n+ 1 ];
arr[ 1 ] = 4 ;
arr[ 2 ] = 7 ;

for ( int i= 3 ; i<=n; i++)
{
// If i is odd
if (i% 2 != 0 )
arr[i] = arr[i/ 2 ]* 10 + 4 ;
else
arr[i] = arr[(i/ 2 )- 1 ]* 10 + 7 ;
}
return arr[n];
}

// main function
public static void main (String[] args)
{
int n = 6 ;
System.out.println(printNthElement(n));
}
}``````

## Python3

``````# Python3 program to find n-th number
# in a series made of digits 4 and 7

# Return n-th number in series made
# of 4 and 7
def printNthElement(n) :

# create an array of size (n + 1)
arr = [ 0 ] * (n + 1 );
arr[ 1 ] = 4
arr[ 2 ] = 7

for i in range ( 3 , n + 1 ) :
# If i is odd
if (i % 2 ! = 0 ) :
arr[i] = arr[i / / 2 ] * 10 + 4
else :
arr[i] = arr[(i / / 2 ) - 1 ] * 10 + 7

return arr[n]

# Driver code
n = 6
print (printNthElement(n))

# This code is contributed by Nikita Tiwari.``````

## C#

``````// C# program to find n-th number in a series
// made of digits 4 and 7
using System;

class GFG
{
// Return n-th number in series made of 4 and 7
static int printNthElement( int n)
{
// create an array of size (n+1)
int []arr = new int [n+1];
arr[1] = 4;
arr[2] = 7;

for ( int i = 3; i <= n; i++)
{
// If i is odd
if (i % 2 != 0)
arr[i] = arr[i / 2] * 10 + 4;
else
arr[i] = arr[(i / 2) - 1] * 10 + 7;
}
return arr[n];
}

// Driver code
public static void Main ()
{
int n = 6;
Console.Write(printNthElement(n));
}
}

// This code is contributed by vt_m.``````

## 的PHP

``````<?php
// PHP program to find n-th
// number in a series
// made of digits 4 and 7

// Return n-th number in
// series made of 4 and 7
function printNthElement( \$n )
{

// create an array
// of size (n+1)
\$arr [1] = 4;
\$arr [2] = 7;

for ( \$i = 3; \$i <= \$n ; \$i ++)
{

// If i is odd
if ( \$i % 2 != 0)
\$arr [ \$i ] = \$arr [ \$i / 2] *
10 + 4;
else
\$arr [ \$i ] = \$arr [( \$i / 2) - 1] *
10 + 7;
}
return \$arr [ \$n ];
}

// Driver code
\$n = 6;
echo (printNthElement( \$n ));

// This code is contributed by Ajit.
?>``````

``77``