Last active
May 13, 2022 07:41
-
-
Save ironpython2001/ef21a4ae69feb1c6ab51f36f6e587a8a to your computer and use it in GitHub Desktop.
Add One to an Array as a Number in c#
This file contains hidden or 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
//Add One to an Array as a Number | |
//Input Result | |
//[1, 3, 2, 4] [1, 3, 2, 5] | |
//[1, 4, 8, 9] [1, 4, 9, 0] | |
//[9, 9, 9, 9] [1, 0, 0, 0, 0] | |
var lst = new List<int> { 1, 4, 8, 9 }; | |
var one = 1; | |
var revlst = lst.ToArray().Reverse().ToList(); | |
var reslst = new List<int>(); | |
int temp = 0; | |
int idx = 0; | |
foreach (var i in revlst) | |
{ | |
int addres; | |
if (idx ==0) | |
{ | |
addres = i + one; | |
} | |
else | |
{ | |
addres = i + temp; | |
} | |
idx++; | |
var straddres = addres.ToString(); | |
if (straddres.Length > 1) | |
{ | |
var lastdigit = straddres.Substring(straddres.Length - 1); | |
var remdigits = straddres.Substring(0, straddres.Length - 1); | |
temp = int.Parse(remdigits); | |
reslst.Add(int.Parse(lastdigit)); | |
} | |
else | |
{ | |
temp = 0; | |
reslst.Add(addres); | |
} | |
if((idx==revlst.Count())&& (temp!=0)) | |
reslst.Add(temp); | |
} | |
var res2 = reslst.ToArray().Reverse().ToList(); | |
foreach(var i in res2) | |
{ | |
Console.WriteLine(i); | |
} | |
/////////////////////////////////////////////// alternative solution /////////////////////////////////////// | |
var input = new List<int> { 9, 9, 9, 9 }; | |
var strinput = string.Empty; | |
input.ForEach(x => strinput = strinput + x); | |
var intinput = int.Parse(strinput); | |
var intresult = intinput + 1; | |
var strresult = intresult.ToString(); | |
var result = new List<int>(); | |
strresult.ToCharArray().ToList().ForEach(x => | |
{ | |
result.Add(int.Parse(x.ToString())); | |
}); | |
result.ForEach(x => Console.WriteLine(x)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment