Skip to content

Instantly share code, notes, and snippets.

@cb372
Created October 23, 2011 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cb372/1306915 to your computer and use it in GitHub Desktop.
Save cb372/1306915 to your computer and use it in GitHub Desktop.
CodeJam 問題C. ビット数 second attempt
def calcAandB(N:BigInt):(BigInt,BigInt) = {
def setIth(i: Int, a:BigInt, b:BigInt, carry:Boolean):(BigInt, BigInt, Boolean) =
(N.bitLength-i, carry) match {
case (n,_) if n<1 => (a,b,carry) // finished all bits of N
case (1,true) => (a,b,carry) // finished all bit of N except msb, and there is no carry
case (n,_) => { // recurse
// handle the carry
val (n_i, c) = (N.testBit(i), carry) match {
case (true, true) => (false, false)
case (false, true) => (true, true)
case (i,c) => (i,c)
}
if (n_i)
setIth(i+1, a.setBit(i), b, c)
else
setIth(i+1, a.setBit(i), b.setBit(i), true)
}
}
val (a,b,carry) = setIth(0, BigInt(0), BigInt(0), false)
(a,b)
}
def findMax(N:BigInt):Int = {
val (a,b) = calcAandB(N)
a.bitCount + b.bitCount
}
import scala.io.Source
val lines = Source.fromFile("C-large-practice.in").getLines()
lines.toList.tail.zipWithIndex.foreach{ valAndIndex => println("Case #"+(valAndIndex._2+1)+": "+findMax(BigInt(valAndIndex._1))) }
@cb372
Copy link
Author

cb372 commented Oct 23, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment