Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is "!" means in this function?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

! 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading