Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Make all array elements even by replacing adjacent pair of array elements with their sum
Next article icon

Modify a given array by replacing each element with the sum or product of their digits based on a given condition

Last Updated : 16 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers, the task is to modify the array elements after performing only one of the following operations on each array elements:

  • If the count of even digits is greater than the count of odd digits in an array element, then update that element to the sum of all the digits of that element.
  • Otherwise, update that element to the product of all the digits of that element.

Examples:

Input: arr[] = {113, 141, 214, 3186}
Output: 3 4 7 3186
Explanation:
Following are the operation performed on each array elements:

  1. For element arr[0](= 113): count of even and odd digits are 0 and 3. As count of even < count of odd digit, therefore update arr[0](= 113) to the product of each digit of the number 113 i.e., 1 * 1 * 3 = 3.
  2. For element arr[1](= 141): count of even and odd digits are 1 and 2. As count of even < count of odd digit, therefore update arr[1](= 141) to the product of each digit of the number 141 i.e., 1 * 4 * 1 = 4.
  3. For element arr[2]:(= 214) count of even and odd digits are 2 and 1. As count of even > count of odd digit, therefore update arr[2](= 214) to the sum of each digit of the number 214 i.e., 2 + 1 + 4 = 7.
  4. For element arr[3](= 3186): count of even and odd digits are 2 and 2. As count of even is the same as the count of odd digit, then no operation is performed. Therefore, arr[3](= 3186) remains the same.

After the above operations, the array modifies to {3, 4, 7, 3186}.

Input: arr[] = {2, 7, 12, 22, 110}
Output: 2 7 12 4 0

Approach: The given problem can be solved by performing the given operations for each array element and print the result accordingly. Follow the steps below to solve the problem:

  • Traverse the given array arr[] and perform the following steps:
    • Find the count of even and odd digits of the current element of the array.
    • If the count of even and odd digits are the same, then no operation is needed to perform.
    • If the count of even digits is greater than the count of odd digits in an array element, then update that element to the sum of all the digits of that element.
    • Otherwise, update that element to the product of all the digits of that element.
  • After completing the above steps, print the array arr[] as the modified array.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to modify the given array // as per the given conditions void evenOdd(int arr[], int N) {     // Traverse the given array arr[]     for (int i = 0; i < N; i++) {          // Initialize the count of even         // and odd digits         int even_digits = 0;         int odd_digits = 0;          // Initialize temp with the         // current array element         int temp = arr[i];          // For count the number of         // even digits         while (temp) {              // Increment the odd count             if ((temp % 10) & 1)                 odd_digits++;              // Otherwise             else                 even_digits++;              // Divide temp by 10             temp /= 10;         }          // Performe addition         if (even_digits > odd_digits) {              int res = 0;             while (arr[i]) {                  res += arr[i] % 10;                 arr[i] /= 10;             }             cout << res << " ";         }          // Performe multiplication         else if (odd_digits > even_digits) {              int res = 1;             while (arr[i]) {                  res *= arr[i] % 10;                 arr[i] /= 10;             }             cout << res << " ";         }          // Otherwise         else             cout << arr[i] << " ";     } }  // Driver Code int main() {     int arr[] = { 113, 141, 214, 3186 };     int N = sizeof(arr) / sizeof(arr[0]);     evenOdd(arr, N);      return 0; } 
Java
// Java program for the above approach  import java.io.*;  class GFG {      // Function to modify the given array     // as per the given conditions     static void evenOdd(int[] arr, int N)     {         // Traverse the given array arr[]         for (int i = 0; i < N; i++) {              // Initialize the count of even             // and odd digits             int even_digits = 0;             int odd_digits = 0;              // Initialize temp with the             // current array element             int temp = arr[i];              // For count the number of             // even digits             while (temp > 0) {                  // Increment the odd count                 if ((temp % 10) % 2 != 0)                     odd_digits++;                  // Otherwise                 else                     even_digits++;                  // Divide temp by 10                 temp /= 10;             }              // Performe addition             if (even_digits > odd_digits) {                  int res = 0;                 while (arr[i] > 0) {                      res += arr[i] % 10;                     arr[i] /= 10;                 }                 System.out.print(res + " ");             }              // Performe multiplication             else if (odd_digits > even_digits) {                  int res = 1;                 while (arr[i] > 0) {                      res *= arr[i] % 10;                     arr[i] /= 10;                 }                 System.out.print(res + " ");             }              // Otherwise             else                 System.out.print(arr[i] + " ");         }     }      // Driver Code     public static void main(String[] args)     {         int[] arr = { 113, 141, 214, 3186 };         int N = arr.length;         evenOdd(arr, N);     } }  // This code is contributed by rishavmahato348. 
Python3
 # Python program for the above approach  # Function to modify the given array # as per the given conditions def evenOdd(arr,N):        # Traverse the given array arr[]     for i in range(N):          # Initialize the count of even         # and odd digits         even_digits = 0;         odd_digits = 0;          # Initialize temp with the         # current array element         temp = arr[i];          # For count the number of         # even digits         while (temp):              # Increment the odd count             if ((temp % 10) & 1):                 odd_digits += 1;              # Otherwise             else:                 even_digits += 1;              # Divide temp by 10             temp = temp//10          # Performe addition         if (even_digits > odd_digits):              res = 0;             while (arr[i]):                  res += arr[i] % 10;                 arr[i] = arr[i]//10;                  print(res, end=" ");          # Performe multiplication         elif (odd_digits > even_digits):              res = 1;             while (arr[i]):                  res *= arr[i] % 10;                 arr[i] = arr[i]//10                          print(res, end=" ");                  # Otherwise         else:             print(arr[i], end=" ");      # Driver Code arr = [113, 141, 214, 3186 ]; N = len(arr); evenOdd(arr, N);      # This code is contributed by _saurabh_jaiswal 
C#
// C# program for the above approach  using System;  class GFG {      // Function to modify the given array     // as per the given conditions     static void evenOdd(int[] arr, int N)     {         // Traverse the given array arr[]         for (int i = 0; i < N; i++) {              // Initialize the count of even             // and odd digits             int even_digits = 0;             int odd_digits = 0;              // Initialize temp with the             // current array element             int temp = arr[i];              // For count the number of             // even digits             while (temp > 0) {                  // Increment the odd count                 if ((temp % 10) % 2 != 0)                     odd_digits++;                  // Otherwise                 else                     even_digits++;                  // Divide temp by 10                 temp /= 10;             }              // Performe addition             if (even_digits > odd_digits) {                  int res = 0;                 while (arr[i] > 0) {                      res += arr[i] % 10;                     arr[i] /= 10;                 }                 Console.Write(res + " ");             }              // Performe multiplication             else if (odd_digits > even_digits) {                  int res = 1;                 while (arr[i] > 0) {                      res *= arr[i] % 10;                     arr[i] /= 10;                 }                 Console.Write(res + " ");             }              // Otherwise             else                 Console.Write(arr[i] + " ");         }     }      // Driver Code     public static void Main()     {         int[] arr = { 113, 141, 214, 3186 };         int N = arr.Length;         evenOdd(arr, N);     } }  // This code is contributed by subham348. 
JavaScript
 <script>    // JavaScript program for the above approach  // Function to modify the given array // as per the given conditions function evenOdd(arr,N) {     // Traverse the given array arr[]     for (let i = 0; i < N; i++) {          // Initialize the count of even         // and odd digits         let even_digits = 0;         let odd_digits = 0;          // Initialize temp with the         // current array element         let temp = arr[i];          // For count the number of         // even digits         while (temp) {              // Increment the odd count             if ((temp % 10) & 1)                 odd_digits++;              // Otherwise             else                 even_digits++;              // Divide temp by 10             temp = parseInt(temp/10)         }          // Performe addition         if (even_digits > odd_digits) {              let res = 0;             while (arr[i]) {                  res += arr[i] % 10;                 arr[i] = parseInt(arr[i]/10);             }             document.write(res+" ");         }          // Performe multiplication         else if (odd_digits > even_digits) {              let res = 1;             while (arr[i]) {                  res *= arr[i] % 10;                 arr[i] = parseInt(arr[i]/10)             }             document.write(res+" ");         }          // Otherwise         else         document.write(arr[i]+" ");     } }  // Driver Code      let  arr = [113, 141, 214, 3186 ];     let N = arr.length;     evenOdd(arr, N);          // This code is contributed by Potta Lokesh    </script> 

Output: 
3 4 7 3186

 

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Make all array elements even by replacing adjacent pair of array elements with their sum
author
subhammahato348
Improve
Article Tags :
  • Mathematical
  • Python
  • DSA
  • Arrays
  • number-digits
  • array-rearrange
Practice Tags :
  • Arrays
  • Mathematical
  • python

Similar Reads

  • Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
    Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the
    12 min read
  • Modify array to another given array by replacing array elements with the sum of the array
    Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: In
    13 min read
  • Count pairs in an array having sum of elements with their respective sum of digits equal
    Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that sati
    8 min read
  • Make all array elements even by replacing adjacent pair of array elements with their sum
    Given an array arr[] of size N, the task is to make all array elements even by replacing a pair of adjacent elements with their sum. Examples: Input: arr[] = { 2, 4, 5, 11, 6 }Output: 1Explanation:Replacing a pair (arr[2], arr[3]) with their sum ( = 5 + 11 = 16) modifies arr[] to { 2, 4, 16, 16, 6 }
    8 min read
  • Check if Arrays can be made equal by Replacing elements with their number of Digits
    Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1,
    10 min read
  • Count of Array elements divisible by either their product or sum of digits
    Given an array arr[]. The task is to count the elements in the array that are divisible by either their product of digits or the sum of digits. Example: Input: arr[] = {123, 25, 36, 7}Output: 2Explanation: Following are the elements that follows the given conditionsSum of digits of 123 is 6 and the
    6 min read
  • Modify array to another given array by replacing array elements with the sum of the array | Set-2
    Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES
    10 min read
  • Minimum value by which each Array element must be added as per given conditions
    Given 2 arrays A[] and B[] and an integer M. The task is to find the minimum value of X such that after changing all the elements of the array to (arr[i] + X)%M frequency of all the elements of A[] is same as the frequency of all the elements of B[]. Print "-1" if it is not possible to find any valu
    8 min read
  • Smallest array that can be obtained by replacing adjacent pairs with their products
    Given an array arr[] of size N, the task is to print the least possible size the given array can be reduced to by performing the following operations: Remove any two adjacent elements, say arr[i] and arr[i+1] and insert a single element arr[i] * arr[i+1] at that position in the array.If all array el
    4 min read
  • Check if sum of array can be made equal to X by removing either the first or last digits of every array element
    Given an array arr[] consisting of N positive integers and a positive integer X, the task is to check if the sum of the given array can be made equal to X by removing either the first or last digit of every array element. If it is possible to make the sum of array elements equal to X, then print "Ye
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences