def checkHappynumber(n: Int): Boolean = {
val set = scala.collection.mutable.HashSet[Int]()
var num: Int = n
while(num != 1) {
var newnum: Int = 0
while (num != 0) {
newnum = (num % 10) * (num % 10)
num /= 10
}
if(!set.add(newnum)){
return false;
}
num = newnum
}
return true
}
What's "!" role in there? the if(!set.add(newnum))? I know that hashset can't have repeated value. The only question is how "!" works here.
CodePudding user response:
!
is a negation operator (!true
is false
, !false
is true
). HashSet.add
returns true
if element was not present in the set (successfully added), false
otherwise. This code returns false
if element was already present in the hashset (trying to add it for the second time).
Here's documentation of add
method.