Last active
February 9, 2021 06:28
-
-
Save roachadam/08e673c86e89d3c1bb1423537a236ff8 to your computer and use it in GitHub Desktop.
My solutions to a "Google" Coding Question: https://www.youtube.com/watch?v=uQdy914JRKQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace GoogleQuestion | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Solution one - cheap way | |
int[] arr = new[] { 9, 9, 9 }; | |
int tmp = 0; | |
string convertMe = string.Empty; | |
for (int i = 0; i < arr.Length; i++) | |
convertMe += arr[i]; | |
tmp = int.Parse(convertMe) + 1; | |
string back = tmp.ToString(); | |
int[] newArr = new int[back.Length]; | |
for (int i = 0; i < newArr.Length; i++) | |
newArr[i] = int.Parse(back[i].ToString()); | |
// Solution two - more complicated, but more logical | |
// Original array | |
arr = new[] {9,9,9}; | |
// 10^3, 10^2, 10^1, 10^0 | |
int originalNumber = 0; | |
for (int i = 0; i < arr.Length; i++) | |
{ | |
// Here I think of each position of the number in powers of 10 | |
// multiplier will be based on the position of the number in the array | |
// Then multiply the mulitplier by the number in the array, and add up the values to get the actual number representation | |
int multiplier = (int)Math.Pow(10, arr.Length - 1 - i); | |
int value = arr[i] * multiplier; | |
originalNumber += value; | |
} | |
// Increment array value by one | |
originalNumber += 1; | |
// If last number in original array is 9, adding one must increase new array size by one | |
bool sizeChange = arr[arr.Length - 1] == 9; | |
// If size change is needed, set new array size to be 1 element larger, otherwise keep same size | |
int arrSize = sizeChange ? arr.Length + 1 : arr.Length; | |
// Declare our new array | |
int[] newArray = new int[arrSize]; | |
for (int i = 0; i < newArray.Length; i++) | |
{ | |
// Here we do the opposite of the first loop. | |
// Get the remainder of dividing the new number by 10 to get the individual digits. | |
int digit = originalNumber % 10; | |
originalNumber = originalNumber / 10; | |
// Numbers will be pinched off in reverse order, so insertion to the newarray must be done reversed as well. | |
newArray[newArray.Length - 1 - i] = digit; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment