Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This method returns true if the number passed in contains a 1.

public boolean hasOne(int n) {
  return (n + "").contains("1");
}

What is the purpose of the + "" part? How does that make n a string? (.contains only works with Strings as far as I understand).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

An int is a primitive. Adding a primitive to a string will perform an implicit conversion of that primitive to a String and add the two strings together. In this case, the int is converted and "" ( empty String ) is added,

That can be rewritten as:

return Integer.toString(n).contains("1");

or

return String.valueOf(n).contains("1");

or

return String.format("%d", n).contains("1");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...