Find the number on the card that remains in the end after performing the given operations
Given an integer N which represents the number of cards in a deck. The deck is ordered from 1 to N where 1 is the topmost card and N is at the bottom. You take out the topmost card from the deck and insert it at the bottom and throw the next card that appears at the top of the deck. Again you do the same thing until a single card remains. The task is to find the number of the card that remains at the end.
Examples:
Input: N = 4
Output: 1
1 2 3 4
^ ^
Top Bottom
Operation 1: 3 4 1 (1 got shifted to the bottom and 2 got removed)
Operation 2: 1 3 (3 got shifted and 4 got removed)
Operation 3: 1 (3 got removed after shifting 1)
Input: N = 10
Output: 5
Approach:
- First of all insert numbers from 1 to N in a queue.
- Now, dequeue the front element from the queue and enqueue it at the end.
- Finally, pop the element at the front.
- Print the final element left in the queue.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int remainingCard( int n)
{
queue< int > queCards;
for ( int i = 1; i <= n; i++)
queCards.push(i);
while ((( int )queCards.size()) >= 2) {
queCards.push(queCards.front());
queCards.pop();
queCards.pop();
}
return queCards.front();
}
int main()
{
int n = 10;
cout << remainingCard(n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int remainingCard( int n)
{
Queue<Integer> queCards = new LinkedList<>();
for ( int i = 1 ; i <= n; i++)
{
queCards.add(i);
}
while ((( int ) queCards.size()) >= 2 )
{
queCards.add(queCards.peek());
queCards.remove();
queCards.remove();
}
return queCards.peek();
}
public static void main(String[] args)
{
int n = 10 ;
System.out.println(remainingCard(n));
}
}
|
Python3
def remainingCard(n):
queCards = []
for i in range ( 1 , n + 1 ):
queCards.append(i)
while ( len (queCards) > = 2 ):
queCards.append(queCards[ 0 ]);
queCards.pop( 0 );
queCards.pop( 0 );
return queCards[ 0 ]
n = 10
print (remainingCard(n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int remainingCard( int n)
{
Queue< int > queCards = new Queue< int >();
for ( int i = 1; i <= n; i++)
{
queCards.Enqueue(i);
}
while ((( int ) queCards.Count) >= 2)
{
queCards.Enqueue(queCards.Peek());
queCards.Dequeue();
queCards.Dequeue();
}
return queCards.Peek();
}
public static void Main(String[] args)
{
int n = 10;
Console.WriteLine(remainingCard(n));
}
}
|
Javascript
<script>
function remainingCard(n)
{
queCards = [];
for ( var i = 1; i <= n; i++)
queCards.push(i);
while ((queCards.length) >= 2) {
queCards.push(queCards[0]);
queCards.shift();
queCards.shift();
}
return queCards[0];
}
var n = 10;
document.write( remainingCard(n));
</script>
|
Last Updated :
15 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...