Created
October 23, 2011 05:27
-
-
Save cb372/1306915 to your computer and use it in GitHub Desktop.
CodeJam 問題C. ビット数 second attempt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The question is here: http://code.google.com/codejam/contest/dashboard?c=889487#s=p2