Minimum number of digits to be removed so that no two consecutive digits are same
Given a number N. The task is to count the minimum number of digits to be removed from the number so that no two consecutive digits are the same.
Examples:
Input : N = 11344
Output : 2
Explanation : Remove the digit 1 from 2nd place and 4 from the end so that the number becomes 134. Thus no two consecutive digits are same. Hence answer is 2.
Input : N = 55553
Output : 3
Explanation : Remove the digit 5 from the 2nd, 3rd and 4th places so that the number becomes 53. Thus no two consecutive digits are same. Hence answer is 3.
The problem can be easily solved if we just count the number of consecutive pairs of equal digits. That would be the minimum number of digits to remove from the given number so that no two consecutive digits are the same.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countConsecutive( int n)
{
string s = to_string(n);
int count = 0;
for ( int i = 0; i < s.size() - 1; i++)
if (s[i] == s[i + 1])
count++;
return count;
}
int main()
{
int n = 44522255;
cout << countConsecutive(n);
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class GFG
{
static int countConsecutive( int n)
{
String s = Integer.toString(n);
int count = 0 ;
for ( int i = 0 ; i < s.length() - 1 ; i++)
if (s.charAt(i) == s.charAt(i + 1 ))
count++;
return count;
}
public static void main(String args[])
{
int n = 44522255 ;
System.out.println(countConsecutive(n));
}
}
|
Python 3
def countConsecutive(n):
s = str (n)
count = 0
for i in range ( len (s) - 1 ):
if (s[i] = = s[i + 1 ]):
count + = 1
return count
if __name__ = = "__main__" :
n = 44522255
print ( countConsecutive(n))
|
C#
using System;
class GFG
{
static int countConsecutive( int n)
{
string s = n.ToString();
int count = 0;
for ( int i = 0; i < s.Length - 1; i++)
if (s[i] == s[i + 1])
count++;
return count;
}
public static void Main()
{
int n = 44522255;
Console.Write(countConsecutive(n));
}
}
|
PHP
<?php
function countConsecutive( $n )
{
$s = (string)( $n );
$len = strlen ( $s );
$count = 0;
for ( $i = 0; $i < $len - 1; $i ++)
if ( $s [ $i ] == $s [ $i + 1])
$count ++;
return $count ;
}
$n = 44522255;
echo countConsecutive( $n );
?>
|
Javascript
<script>
function countConsecutive(n)
{
var s = n.toString();
var count = 0;
for ( var i = 0; i < s.length - 1; i++)
if (s[i] == s[i + 1])
count++;
return count;
}
var n = 44522255;
document.write( countConsecutive(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(logn)
Last Updated :
07 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...