Although, this is a trivial function, my question here is more general. I'm more than happy to share solutions to problems I face, but it seems unfair to accept them as an answer when someone else gave the hint to write it. What is the right way to deal with this on StackOverflow?
If someone else's hint/comment aided you in formulating an answer then link to source.
If there is no link available to the actual hint, you can always link to the users profile.
There is no need to "feel bad" or to think that it is "unfair" to include information you got from someone else as long as you give credit where it is needed. The point is to help people, now and in the future. A person reading your post will be happy that a complete solution is present and not have to piece together comments and posts to reach the final answer.
With regard to accepting your own answer in these cases, you can always upvote someone else's answer if it helped you.
Add it. If it is valuable information which improves (on) the content already there, nothing should stop you from adding it. You might decide not to change the accepted answer to yours if you feel that's unfair, but don't avoid posting what might be valuable content.