- A mileage counter is used to measure mileage in an automobile. A mileage counter looks something like this 0 5 9 9 8 The above mileage counter says that the car has travelled 5,998 miles. Each mile travelled by the automobile increments the mileage counter. Here is how the above mileage counter changes over a 3 mile drive. After the first mile 0 5 9 9 9
After the second mile 0 6 0 0 0
After the third mile 0 6 0 0 1
A mileage counter can be represented as an array. The mileage counter 0 5 9 9 8 can be represented as the array int a[ ] = new int[ ] {8, 9, 9, 5, 0} Note that the mileage counter is "backwards" in the array, a[0] represents ones, a[1] represents tens, a[2] represents hundreds, etc. Write a function named updateMileage that takes an array representation of a mileage counter (which can be arbitrarily long) and adds a given number of miles to the array. Since arrays are passed by reference you can update the array in the function, you do not have to return the updated array.
Note that the mileage counter wraps around if it reaches all 9s and there is still some mileage to add.
if the input array is {9, 9, 9, 9, 9, 9, 9, 9, 9, 9} and the mileage is 13 the array becomes {2, 1, 0, 0, 0, 0, 0, 0, 0, 0}
i tried to solve this problem but am not being able to solve it , how can i do this ? if anybody could help me i would be thankful
using System;
using System.Collections.Generic;
using System.Text;
namespace updateMileageCounter
{
class Program
{
static void Main(string[] args)
{
//System.Console.WriteLine(updateMileageCounter(new int[] { 8, 9, 9, 5, 0 }, 1));
//System.Console.WriteLine(updateMileageCounter(new int[] { 8, 9, 9, 5, 0 }, 2));
foreach (int a1 in updateMileageCounter(new int[] { 8, 9, 9, 5, 0 }, 13))
{
System.Console.WriteLine(a1);
}
}
static int[] updateMileageCounter(int[] a, int miles)
{
int remain = miles;
int[] result = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
result[i] =a[i] + remain;
if (i == a.Length - 1 && result[i] > 9)
{
remain = result[i] - 9;
for (i = 0; i < a.Length; i++)
{
result[i] = 0;
a[i] = 0;
}
if (remain == 1)
{
return result;
}
for (i = 0; i < a.Length; i++)
{
result[i] =a[i] + remain;
if (result[i] > 9)
{
decimal res = result[i] / 10;
result[i] = (result[i] - 1)-10;
}
}
return result;
}
if (result[i] > 9)
{
remain = result[i] - 9;
result[i] = 0;
}
else if (result[i] < 9 || result[i]==9)
{
remain = 0;
}
}
return result;
}
}
}