Programming Challenges

Pho3nix

The Legend
Joined
Jul 31, 2009
Messages
30,589
[)roi(];17687286 said:
Is this a parser for string calculator? i.e. given the following string "1 + 4 - 3" you return 2?
Or is this to simply add the successive digits in a given string "123" to return 6?

The latter but you are given an integer, not a string.
I convert it to a string, so I can access the separate digits :eek:
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Again I didn't bother to run this through VS... so a bug could be possible.
Code:
public static int sumDigits(int value)
{
   var numbers = value.ToString().ToCharArray().Select(x => int.Parse(x.ToString()));
   return numbers.Aggregate((a, b) => b + a);
}

Note: don't forget to include for linq: "using System.Linq;"

alternatively you could use "GetNumericValue"

Code:
public static int SumDigits(int value)
{
    var numbers = value.ToString().ToCharArray().Select(x => Char.GetNumericValue(x));
    return (int)numbers.Aggregate((a, b) => b + a);
}
 
Last edited:

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,886
[)roi(];17687068 said:
Cool, but you could have also done it with an array: ToCharArray() and Linq (Select & Where)

Here e.g. is the same in Swift; using an array and higher order functions (i.e. similar concept to Linq).
Code:
extension String
{
  func isPalindrome() -> Bool {
    let lower = self.lowercaseString.unicodeScalars.filter
      { 97...122 ~= Int($0.value) }.map { String($0) }.joinWithSeparator("")
    return lower == String(lower.characters.reverse())
  }
}

"Noel sees Leon.".isPalindrome() // true

C# Linq version example, hopefully code correct; didn't bother to run it through VS.
Code:
public static bool IsPalindrome(string str)
{
   var onlyLetters = str.ToLower().Where(c => Char.IsLetter(c)).ToArray();
   return new String(onlyLetters) == new String(onlyLetters.Reverse());
}

Getting a weird error on that one. Can't figure it out.

Compiler:
Compiler output:
Palindrome.cs(7,36): error CS1061: 'string' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

Capture.jpg
 

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,886
Yup bravo, works perfectly. I should have come here for the interview hehe! Well I got the job anyway, that was a long time ago. Fun times.

Capture.jpg
 
Top