C#: Compute the sum of two given non-negative integers x and y as long as the sum has the same number of digits as x
Sum of Integers with Same Digit Count
Write a C# Sharp program to compute the sum of two given non-negative integers x and y as long as the sum has the same number of digits as x. If the sum has more digits than x return x without y.
Visual Presentation:

Sample Solution:-
C# Sharp Code:
using System; // Import the System namespace which contains fundamental types and base classes
using System.Linq; // Import the LINQ namespace for LINQ functionality
namespace exercises // Define a namespace called 'exercises'
{
class Program // Define a class named 'Program'
{
static void Main(string[] args) // The entry point of the program
{
// Output the result of test function with different integer arguments
Console.WriteLine(test(4, 5)); // Test with integers 4 and 5
Console.WriteLine(test(7, 4)); // Test with integers 7 and 4
Console.WriteLine(test(10, 10)); // Test with integers 10 and 10
Console.ReadLine(); // Wait for user input before closing the console window
}
// Function definition of test function that takes two integers 'x' and 'y' and returns an integer
public static int test(int x, int y)
{
// Check if the length of the sum of 'x' and 'y' converted to a string is greater than the length of 'x' converted to a string
// If true, return 'x'; otherwise, return the sum of 'x' and 'y'
return (x + y).ToString().Length > x.ToString().Length ? x : x + y;
}
}
}
Sample Output:
9 7 20
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C# program to sum two integers and return the smaller one if the sum has more digits than both numbers.
- Write a C# program to return the sum only if it ends with the same number of digits as the larger input number.
- Write a C# program to add two numbers and truncate the result if it exceeds the digit count of either input.
- Write a C# program to compute the sum only if both numbers have the same digit count and the sum is even.
Go to:
PREV : Digit Appears in Both Integers.
NEXT : Sum of Three Integers or Return Third if Two Match.
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.