Count of matchsticks required to represent the given number
Last Updated :
10 Mar, 2022
Given a large integer as a string str, the task is find the number of matchsticks required to represent it.
Examples:
Input: str = “56”
Output: 11
5 sticks are required to represent 5 and
6 sticks are required to represent 6.
Input: str = “548712458645878”
Output: 74
Approach: Store the count of match sticks required to represent every digit from 0 to 9 in an array sticks[]. Now traverse the given string digit by digit and add the count of sticks required for the current digit.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int sticks[] = { 6, 2, 5, 5, 4, 5,
6, 3, 7, 6 };
int countSticks(string str, int n)
{
int cnt = 0;
for ( int i = 0; i < n; i++) {
cnt += (sticks[str[i] - '0' ]);
}
return cnt;
}
int main()
{
string str = "56" ;
int n = str.length();
cout << countSticks(str, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int sticks[] = { 6 , 2 , 5 , 5 , 4 , 5 ,
6 , 3 , 7 , 6 };
static int countSticks(String str, int n)
{
int cnt = 0 ;
for ( int i = 0 ; i < n; i++)
{
cnt += (sticks[str.charAt(i) - '0' ]);
}
return cnt;
}
public static void main(String []args)
{
String str = "56" ;
int n = str.length();
System.out.println(countSticks(str, n));
}
}
|
Python3
sticks = [ 6 , 2 , 5 , 5 , 4 , 5 ,
6 , 3 , 7 , 6 ];
def countSticks(string, n) :
cnt = 0 ;
for i in range (n) :
cnt + = (sticks[ ord (string[i]) - ord ( '0' )]);
return cnt;
if __name__ = = "__main__" :
string = "56" ;
n = len (string);
print (countSticks(string, n));
|
C#
using System;
class GFG
{
static int []sticks = { 6, 2, 5, 5, 4, 5,
6, 3, 7, 6 };
static int countSticks(String str, int n)
{
int cnt = 0;
for ( int i = 0; i < n; i++)
{
cnt += (sticks[str[i] - '0' ]);
}
return cnt;
}
public static void Main(String []args)
{
String str = "56" ;
int n = str.Length;
Console.WriteLine(countSticks(str, n));
}
}
|
Javascript
<script>
var sticks = [ 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 ]
function countSticks(str, n)
{
var cnt = 0;
for ( var i = 0; i < n; i++) {
cnt += (sticks[str[i] - '0' ]);
}
return cnt;
}
var str = "56" ;
var n = str.length;
document.write(countSticks(str, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...