id
stringlengths
2
6
java
stringlengths
48
5.92k
python
stringlengths
33
11.1k
T40300
public final class p174 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p174 ( ) . run ( ) ) ; } private static final int SIZE_LIMIT = 1000000 ; private static final int TYPE_LIMIT = 10 ; public String run ( ) { int [ ] type = new int [ SIZE_LIMIT + 1 ] ; for ( int n = 3 ; ( n - 1 ) * 4 <= SIZE_LIMIT ; n ++ ) { for ( int m = n - 2 ; m >= 1 ; m -= 2 ) { int tiles = n * n - m * m ; if ( tiles > SIZE_LIMIT ) break ; type [ tiles ] ++ ; } } int count = 0 ; for ( int t : type ) { if ( 1 <= t && t <= TYPE_LIMIT ) count ++ ; } return Integer . toString ( count ) ; } }
def compute ( ) : NEW_LINE INDENT SIZE_LIMIT = 1000000 NEW_LINE TYPE_LIMIT = 10 NEW_LINE type = [ 0 ] * ( SIZE_LIMIT + 1 ) NEW_LINE for n in range ( 3 , SIZE_LIMIT // 4 + 2 ) : NEW_LINE INDENT for m in range ( n - 2 , 0 , - 2 ) : NEW_LINE INDENT tiles = n * n - m * m NEW_LINE if tiles > SIZE_LIMIT : NEW_LINE INDENT break NEW_LINE DEDENT type [ tiles ] += 1 NEW_LINE DEDENT DEDENT ans = sum ( 1 for t in type if 1 <= t <= TYPE_LIMIT ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40301
import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public final class p109 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p109 ( ) . run ( ) ) ; } public String run ( ) { points = new ArrayList < > ( ) ; for ( int i = 1 ; i <= 20 ; i ++ ) { for ( int j = 1 ; j <= 3 ; j ++ ) points . add ( i * j ) ; } points . add ( 25 ) ; points . add ( 50 ) ; List < Integer > doublePoints = new ArrayList < > ( ) ; for ( int i = 1 ; i <= 20 ; i ++ ) doublePoints . add ( i * 2 ) ; doublePoints . add ( 25 * 2 ) ; ways = new int [ 3 ] [ 101 ] [ points . size ( ) ] ; for ( int [ ] [ ] x : ways ) { for ( int [ ] y : x ) Arrays . fill ( y , - 1 ) ; } int checkouts = 0 ; for ( int remainingPoints = 1 ; remainingPoints < 100 ; remainingPoints ++ ) { for ( int throwz = 0 ; throwz <= 2 ; throwz ++ ) { for ( int p : doublePoints ) { if ( p <= remainingPoints ) checkouts += ways ( throwz , remainingPoints - p , points . size ( ) - 1 ) ; } } } return Integer . toString ( checkouts ) ; } private List < Integer > points ; private int [ ] [ ] [ ] ways ; private int ways ( int throwz , int total , int maxIndex ) { if ( ways [ throwz ] [ total ] [ maxIndex ] == - 1 ) { int result ; if ( throwz == 0 ) result = total == 0 ? 1 : 0 ; else { result = 0 ; if ( maxIndex > 0 ) result += ways ( throwz , total , maxIndex - 1 ) ; if ( points . get ( maxIndex ) <= total ) result += ways ( throwz - 1 , total - points . get ( maxIndex ) , maxIndex ) ; } ways [ throwz ] [ total ] [ maxIndex ] = result ; } return ways [ throwz ] [ total ] [ maxIndex ] ; } }
def compute ( ) : NEW_LINE INDENT points = [ i * j for i in range ( 1 , 21 ) for j in range ( 1 , 4 ) ] + [ 25 , 50 ] NEW_LINE doublepoints = [ i * 2 for i in range ( 1 , 21 ) ] + [ 25 * 2 ] NEW_LINE ways = [ [ [ None ] * len ( points ) for j in range ( 101 ) ] for i in range ( 3 ) ] NEW_LINE def calc_ways ( throws , total , maxindex ) : NEW_LINE INDENT if ways [ throws ] [ total ] [ maxindex ] is None : NEW_LINE INDENT if throws == 0 : NEW_LINE INDENT result = 1 if total == 0 else 0 NEW_LINE DEDENT else : NEW_LINE INDENT result = 0 NEW_LINE if maxindex > 0 : NEW_LINE INDENT result += calc_ways ( throws , total , maxindex - 1 ) NEW_LINE DEDENT if points [ maxindex ] <= total : NEW_LINE INDENT result += calc_ways ( throws - 1 , total - points [ maxindex ] , maxindex ) NEW_LINE DEDENT DEDENT ways [ throws ] [ total ] [ maxindex ] = result NEW_LINE DEDENT return ways [ throws ] [ total ] [ maxindex ] NEW_LINE DEDENT checkouts = 0 NEW_LINE for remainingpoints in range ( 1 , 100 ) : NEW_LINE INDENT for throws in range ( 3 ) : NEW_LINE INDENT for p in doublepoints : NEW_LINE INDENT if p <= remainingpoints : NEW_LINE INDENT checkouts += calc_ways ( throws , remainingpoints - p , len ( points ) - 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return str ( checkouts ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40302
public final class p023 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p023 ( ) . run ( ) ) ; } private static final int LIMIT = 28123 ; private boolean [ ] isAbundant = new boolean [ LIMIT + 1 ] ; public String run ( ) { for ( int i = 1 ; i < isAbundant . length ; i ++ ) isAbundant [ i ] = isAbundant ( i ) ; int sum = 0 ; for ( int i = 1 ; i <= LIMIT ; i ++ ) { if ( ! isSumOf2Abundants ( i ) ) sum += i ; } return Integer . toString ( sum ) ; } private boolean isSumOf2Abundants ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) { if ( isAbundant [ i ] && isAbundant [ n - i ] ) return true ; } return false ; } private static boolean isAbundant ( int n ) { if ( n < 1 ) throw new IllegalArgumentException ( ) ; int sum = 1 ; int end = Library . sqrt ( n ) ; for ( int i = 2 ; i <= end ; i ++ ) { if ( n % i == 0 ) sum += i + n / i ; } if ( end * end == n ) sum -= end ; return sum > n ; } }
def compute ( ) : NEW_LINE INDENT LIMIT = 28124 NEW_LINE divisorsum = [ 0 ] * LIMIT NEW_LINE for i in range ( 1 , LIMIT ) : NEW_LINE INDENT for j in range ( i * 2 , LIMIT , i ) : NEW_LINE INDENT divisorsum [ j ] += i NEW_LINE DEDENT DEDENT abundantnums = [ i for ( i , x ) in enumerate ( divisorsum ) if x > i ] NEW_LINE expressible = [ False ] * LIMIT NEW_LINE for i in abundantnums : NEW_LINE INDENT for j in abundantnums : NEW_LINE INDENT if i + j < LIMIT : NEW_LINE INDENT expressible [ i + j ] = True NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT ans = sum ( i for ( i , x ) in enumerate ( expressible ) if not x ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40303
public final class p045 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p045 ( ) . run ( ) ) ; } public String run ( ) { int i = 286 ; int j = 166 ; int k = 144 ; while ( true ) { long triangle = ( long ) i * ( i + 1 ) / 2 ; long pentagon = ( long ) j * ( j * 3 - 1 ) / 2 ; long hexagon = ( long ) k * ( k * 2 - 1 ) ; long min = Math . min ( Math . min ( triangle , pentagon ) , hexagon ) ; if ( min == triangle && min == pentagon && min == hexagon ) return Long . toString ( min ) ; if ( min == triangle ) i ++ ; if ( min == pentagon ) j ++ ; if ( min == hexagon ) k ++ ; } } }
def compute ( ) : NEW_LINE INDENT i = 286 NEW_LINE j = 166 NEW_LINE k = 144 NEW_LINE while True : NEW_LINE INDENT triangle = i * ( i + 1 ) // 2 NEW_LINE pentagon = j * ( j * 3 - 1 ) // 2 NEW_LINE hexagon = k * ( k * 2 - 1 ) NEW_LINE minimum = min ( triangle , pentagon , hexagon ) NEW_LINE if minimum == max ( triangle , pentagon , hexagon ) : NEW_LINE INDENT return str ( triangle ) NEW_LINE DEDENT if minimum == triangle : i += 1 NEW_LINE if minimum == pentagon : j += 1 NEW_LINE if minimum == hexagon : k += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40304
import java . math . BigInteger ; public final class p016 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p016 ( ) . run ( ) ) ; } public String run ( ) { String temp = BigInteger . ONE . shiftLeft ( 1000 ) . toString ( ) ; int sum = 0 ; for ( int i = 0 ; i < temp . length ( ) ; i ++ ) sum += temp . charAt ( i ) - '0' ; return Integer . toString ( sum ) ; } }
def compute ( ) : NEW_LINE INDENT n = 2 ** 1000 NEW_LINE ans = sum ( int ( c ) for c in str ( n ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40305
public final class p050 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p050 ( ) . run ( ) ) ; } private static final int LIMIT = Library . pow ( 10 , 6 ) ; public String run ( ) { boolean [ ] isPrime = Library . listPrimality ( LIMIT ) ; int [ ] primes = Library . listPrimes ( LIMIT ) ; long maxSum = 0 ; int maxRun = - 1 ; for ( int i = 0 ; i < primes . length ; i ++ ) { int sum = 0 ; for ( int j = i ; j < primes . length ; j ++ ) { sum += primes [ j ] ; if ( sum > LIMIT ) break ; else if ( j - i > maxRun && sum > maxSum && isPrime [ sum ] ) { maxSum = sum ; maxRun = j - i ; } } } return Long . toString ( maxSum ) ; } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT ans = 0 NEW_LINE isprime = eulerlib . list_primality ( 999999 ) NEW_LINE primes = eulerlib . list_primes ( 999999 ) NEW_LINE consecutive = 0 NEW_LINE for i in range ( len ( primes ) ) : NEW_LINE INDENT sum = primes [ i ] NEW_LINE consec = 1 NEW_LINE for j in range ( i + 1 , len ( primes ) ) : NEW_LINE INDENT sum += primes [ j ] NEW_LINE consec += 1 NEW_LINE if sum >= len ( isprime ) : NEW_LINE INDENT break NEW_LINE DEDENT if isprime [ sum ] and consec > consecutive : NEW_LINE INDENT ans = sum NEW_LINE consecutive = consec NEW_LINE DEDENT DEDENT DEDENT return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40306
public final class p123 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p123 ( ) . run ( ) ) ; } private static final int PRIME_LIMIT = 1000000 ; private static final long THRESHOLD = 10000000000L ; public String run ( ) { int [ ] primes = Library . listPrimes ( PRIME_LIMIT ) ; for ( int n = 5 ; n <= primes . length ; n += 2 ) { long rem = ( long ) n * primes [ n - 1 ] * 2 ; if ( rem > THRESHOLD ) return Integer . toString ( n ) ; } throw new AssertionError ( " Not ▁ found " ) ; } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT primes = eulerlib . list_primes ( 1000000 ) NEW_LINE for n in range ( 5 , len ( primes ) , 2 ) : NEW_LINE INDENT rem = n * primes [ n - 1 ] * 2 NEW_LINE if rem > 10000000000 : NEW_LINE INDENT return str ( n ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40307
public final class p108 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p108 ( ) . run ( ) ) ; } public String run ( ) { for ( int n = 1 ; ; n ++ ) { if ( ( countDivisorsSquared ( n ) + 1 ) / 2 > 1000 ) return Integer . toString ( n ) ; } } private static int countDivisorsSquared ( int n ) { int count = 1 ; for ( int i = 2 , end = Library . sqrt ( n ) ; i <= end ; i ++ ) { if ( n % i == 0 ) { int j = 0 ; do { n /= i ; j ++ ; } while ( n % i == 0 ) ; count *= j * 2 + 1 ; end = Library . sqrt ( n ) ; } } if ( n != 1 ) count *= 3 ; return count ; } }
import eulerlib , itertools NEW_LINE def compute ( ) : NEW_LINE INDENT for n in itertools . count ( 1 ) : NEW_LINE INDENT if ( count_divisors_squared ( n ) + 1 ) // 2 > 1000 : NEW_LINE INDENT return str ( n ) NEW_LINE DEDENT DEDENT DEDENT def count_divisors_squared ( n ) : NEW_LINE INDENT count = 1 NEW_LINE end = eulerlib . sqrt ( n ) NEW_LINE for i in itertools . count ( 2 ) : NEW_LINE INDENT if i > end : NEW_LINE INDENT break NEW_LINE DEDENT if n % i == 0 : NEW_LINE INDENT j = 0 NEW_LINE while True : NEW_LINE INDENT n //= i NEW_LINE j += 1 NEW_LINE if n % i != 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT count *= j * 2 + 1 NEW_LINE end = eulerlib . sqrt ( n ) NEW_LINE DEDENT DEDENT if n != 1 : NEW_LINE INDENT count *= 3 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40308
public final class p114 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p114 ( ) . run ( ) ) ; } private static final int LENGTH = 50 ; public String run ( ) { long [ ] ways = new long [ LENGTH + 1 ] ; ways [ 0 ] = 1 ; ways [ 1 ] = 1 ; ways [ 2 ] = 1 ; for ( int n = 3 ; n <= LENGTH ; n ++ ) { long sum = ways [ n - 1 ] + 1 ; for ( int k = 3 ; k < n ; k ++ ) sum += ways [ n - k - 1 ] ; ways [ n ] = sum ; } return Long . toString ( ways [ LENGTH ] ) ; } }
def compute ( ) : NEW_LINE INDENT LENGTH = 50 NEW_LINE ways = [ 0 ] * ( LENGTH + 1 ) NEW_LINE for n in range ( len ( ways ) ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT ways [ n ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT ways [ n ] = ways [ n - 1 ] + sum ( ways [ : n - 3 ] ) + 1 NEW_LINE DEDENT DEDENT return str ( ways [ - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40309
public final class p030 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p030 ( ) . run ( ) ) ; } public String run ( ) { int sum = 0 ; for ( int i = 2 ; i < 1000000 ; i ++ ) { if ( i == fifthPowerDigitSum ( i ) ) sum += i ; } return Integer . toString ( sum ) ; } private static int fifthPowerDigitSum ( int x ) { int sum = 0 ; while ( x != 0 ) { int y = x % 10 ; sum += y * y * y * y * y ; x /= 10 ; } return sum ; } }
def compute ( ) : NEW_LINE INDENT ans = sum ( i for i in range ( 2 , 1000000 ) if i == fifth_power_digit_sum ( i ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT def fifth_power_digit_sum ( n ) : NEW_LINE INDENT return sum ( int ( c ) ** 5 for c in str ( n ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40310
public final class p010 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p010 ( ) . run ( ) ) ; } private static final int LIMIT = 2000000 ; public String run ( ) { long sum = 0 ; for ( int p : Library . listPrimes ( LIMIT - 1 ) ) sum += p ; return Long . toString ( sum ) ; } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT ans = sum ( eulerlib . list_primes ( 1999999 ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40311
public final class p145 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p145 ( ) . run ( ) ) ; } public String run ( ) { int sum = 0 ; for ( int digits = 1 ; digits <= 9 ; digits ++ ) { if ( digits % 2 == 0 ) sum += 20 * Library . pow ( 30 , digits / 2 - 1 ) ; else if ( digits % 4 == 3 ) sum += 100 * Library . pow ( 500 , ( digits - 3 ) / 4 ) ; else if ( digits % 4 == 1 ) sum += 0 ; else throw new AssertionError ( ) ; } return Integer . toString ( sum ) ; } }
def compute ( ) : NEW_LINE INDENT def count_reversibles ( numdigits ) : NEW_LINE INDENT if numdigits % 2 == 0 : NEW_LINE INDENT return 20 * 30 ** ( numdigits // 2 - 1 ) NEW_LINE DEDENT elif numdigits % 4 == 3 : NEW_LINE INDENT return 100 * 500 ** ( ( numdigits - 3 ) // 4 ) NEW_LINE DEDENT elif numdigits % 4 == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT raise AssertionError ( ) NEW_LINE DEDENT DEDENT ans = sum ( count_reversibles ( d ) for d in range ( 2 , 10 ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40312
public final class p142 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p142 ( ) . run ( ) ) ; } private boolean [ ] isSquare ; public String run ( ) { int sumLimit = 10 ; while ( true ) { isSquare = new boolean [ sumLimit ] ; for ( int i = 0 ; i * i < sumLimit ; i ++ ) isSquare [ i * i ] = true ; int sum = findSum ( sumLimit ) ; if ( sum != - 1 ) { sum = sumLimit ; break ; } sumLimit *= 10 ; } while ( true ) { int sum = findSum ( sumLimit ) ; if ( sum == - 1 ) return Integer . toString ( sumLimit ) ; sumLimit = sum ; } } private int findSum ( int limit ) { for ( int a = 1 ; a * a < limit ; a ++ ) { for ( int b = a - 1 ; b > 0 ; b -- ) { if ( ( a + b ) % 2 != 0 ) continue ; int x = ( a * a + b * b ) / 2 ; int y = ( a * a - b * b ) / 2 ; if ( x + y + 1 >= limit ) continue ; int zlimit = Math . min ( y , limit - x - y ) ; for ( int c = Library . sqrt ( y ) + 1 ; c * c - y < zlimit ; c ++ ) { int z = c * c - y ; if ( isSquare [ x + z ] && isSquare [ x - z ] && isSquare [ y - z ] ) return x + y + z ; } } } return - 1 ; } }
import eulerlib , itertools NEW_LINE def compute ( ) : NEW_LINE INDENT def find_sum ( limit ) : NEW_LINE INDENT for a in itertools . count ( 1 ) : NEW_LINE INDENT if a * a >= limit : NEW_LINE INDENT break NEW_LINE DEDENT for b in reversed ( range ( 1 , a ) ) : NEW_LINE INDENT if ( a + b ) % 2 != 0 : NEW_LINE INDENT continue NEW_LINE DEDENT x = ( a * a + b * b ) // 2 NEW_LINE y = ( a * a - b * b ) // 2 NEW_LINE if x + y + 1 >= limit : NEW_LINE INDENT continue NEW_LINE DEDENT zlimit = min ( y , limit - x - y ) NEW_LINE for c in itertools . count ( eulerlib . sqrt ( y ) + 1 ) : NEW_LINE INDENT z = c * c - y NEW_LINE if z >= zlimit : NEW_LINE INDENT break NEW_LINE DEDENT if issquare [ x + z ] and issquare [ x - z ] and issquare [ y - z ] : NEW_LINE INDENT return x + y + z NEW_LINE DEDENT DEDENT DEDENT DEDENT return None NEW_LINE DEDENT sumlimit = 10 NEW_LINE while True : NEW_LINE INDENT issquare = [ False ] * sumlimit NEW_LINE for i in range ( eulerlib . sqrt ( len ( issquare ) - 1 ) + 1 ) : NEW_LINE INDENT issquare [ i * i ] = True NEW_LINE DEDENT sum = find_sum ( sumlimit ) NEW_LINE if sum is not None : NEW_LINE INDENT sum = sumlimit NEW_LINE break NEW_LINE DEDENT sumlimit *= 10 NEW_LINE DEDENT while True : NEW_LINE INDENT sum = find_sum ( sumlimit ) NEW_LINE if sum is None : NEW_LINE INDENT return str ( sumlimit ) NEW_LINE DEDENT sumlimit = sum NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40313
public final class p020 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p020 ( ) . run ( ) ) ; } public String run ( ) { String temp = Library . factorial ( 100 ) . toString ( ) ; int sum = 0 ; for ( int i = 0 ; i < temp . length ( ) ; i ++ ) sum += temp . charAt ( i ) - '0' ; return Integer . toString ( sum ) ; } }
import math NEW_LINE def compute ( ) : NEW_LINE INDENT n = math . factorial ( 100 ) NEW_LINE ans = sum ( int ( c ) for c in str ( n ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40314
import java . math . BigInteger ; public final class p065 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p065 ( ) . run ( ) ) ; } public String run ( ) { BigInteger n = BigInteger . ONE ; BigInteger d = BigInteger . ZERO ; for ( int i = 99 ; i >= 0 ; i -- ) { BigInteger temp = BigInteger . valueOf ( continuedFractionTerm ( i ) ) . multiply ( n ) . add ( d ) ; d = n ; n = temp ; } int sum = 0 ; while ( ! n . equals ( BigInteger . ZERO ) ) { BigInteger [ ] divrem = n . divideAndRemainder ( BigInteger . TEN ) ; sum += divrem [ 1 ] . intValue ( ) ; n = divrem [ 0 ] ; } return Integer . toString ( sum ) ; } private static int continuedFractionTerm ( int i ) { if ( i == 0 ) return 2 ; else if ( i % 3 == 2 ) return i / 3 * 2 + 2 ; else return 1 ; } }
def compute ( ) : NEW_LINE INDENT numer = 1 NEW_LINE denom = 0 NEW_LINE for i in reversed ( range ( 100 ) ) : NEW_LINE INDENT numer , denom = e_contfrac_term ( i ) * numer + denom , numer NEW_LINE DEDENT ans = sum ( int ( c ) for c in str ( numer ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT def e_contfrac_term ( i ) : NEW_LINE INDENT if i == 0 : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif i % 3 == 2 : NEW_LINE INDENT return i // 3 * 2 + 2 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40315
import java . util . Arrays ; public final class p146 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p146 ( ) . run ( ) ) ; } private static final int LIMIT = 150000000 ; private static long [ ] INCREMENTS = { 1 , 3 , 7 , 9 , 13 , 27 } ; public String run ( ) { long sum = 0 ; for ( int n = 0 ; n < LIMIT ; n += 10 ) { if ( hasConsecutivePrimes ( n ) ) sum += n ; } return Long . toString ( sum ) ; } private static long maxNumber = ( long ) LIMIT * LIMIT + INCREMENTS [ INCREMENTS . length - 1 ] ; private static int [ ] primes = Library . listPrimes ( ( int ) Library . sqrt ( maxNumber ) ) ; private static boolean hasConsecutivePrimes ( int n ) { long n2 = ( long ) n * n ; long [ ] temp = new long [ INCREMENTS . length ] ; for ( int i = 0 ; i < INCREMENTS . length ; i ++ ) temp [ i ] = n2 + INCREMENTS [ i ] ; for ( int p : primes ) { for ( long x : temp ) { if ( x != p && x % p == 0 ) return false ; } } for ( int i = 1 ; i < INCREMENTS [ INCREMENTS . length - 1 ] ; i ++ ) { if ( Arrays . binarySearch ( INCREMENTS , i ) < 0 && isPrime ( n2 + i ) ) return false ; } return true ; } private static boolean isPrime ( long n ) { int end = ( int ) Library . sqrt ( n ) ; for ( int p : primes ) { if ( p > end ) break ; if ( n != p && n % p == 0 ) return false ; } return true ; } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT LIMIT = 150000000 NEW_LINE INCREMENTS = [ 1 , 3 , 7 , 9 , 13 , 27 ] NEW_LINE NON_INCREMENTS = set ( range ( INCREMENTS [ - 1 ] ) ) - set ( INCREMENTS ) NEW_LINE maxnumber = LIMIT ** 2 + INCREMENTS [ - 1 ] NEW_LINE primes = eulerlib . list_primes ( eulerlib . sqrt ( maxnumber ) ) NEW_LINE def has_consecutive_primes ( n ) : NEW_LINE INDENT n2 = n ** 2 NEW_LINE temp = [ ( n2 + k ) for k in INCREMENTS ] NEW_LINE if any ( ( x != p and x % p == 0 ) for p in primes for x in temp ) : NEW_LINE INDENT return False NEW_LINE DEDENT return all ( ( not is_prime ( n2 + k ) ) for k in NON_INCREMENTS ) NEW_LINE DEDENT def is_prime ( n ) : NEW_LINE INDENT end = eulerlib . sqrt ( n ) NEW_LINE for p in primes : NEW_LINE INDENT if p > end : NEW_LINE INDENT break NEW_LINE DEDENT if n % p == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT ans = sum ( n for n in range ( 0 , LIMIT , 10 ) if has_consecutive_primes ( n ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40316
import java . math . BigInteger ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public final class p169 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p169 ( ) . run ( ) ) ; } private static final BigInteger NUMBER = BigInteger . TEN . pow ( 25 ) ; public String run ( ) { return countWays ( NUMBER , NUMBER . bitLength ( ) - 1 , 2 ) . toString ( ) ; } private Map < List < BigInteger > , BigInteger > ways = new HashMap < > ( ) ; private BigInteger countWays ( BigInteger number , int exponent , int repetitions ) { List < BigInteger > key = Arrays . asList ( number , BigInteger . valueOf ( exponent ) , BigInteger . valueOf ( repetitions ) ) ; if ( ways . containsKey ( key ) ) return ways . get ( key ) ; BigInteger result ; if ( exponent < 0 ) result = number . equals ( BigInteger . ZERO ) ? BigInteger . ONE : BigInteger . ZERO ; else { result = countWays ( number , exponent - 1 , 2 ) ; BigInteger pow = BigInteger . ONE . shiftLeft ( exponent ) ; BigInteger upper = pow . multiply ( BigInteger . valueOf ( repetitions + 2 ) ) ; if ( repetitions > 0 && pow . compareTo ( number ) <= 0 && number . compareTo ( upper ) < 0 ) result = result . add ( countWays ( number . subtract ( pow ) , exponent , repetitions - 1 ) ) ; } ways . put ( key , result ) ; return result ; } }
import eulerlib , sys NEW_LINE def compute ( ) : NEW_LINE INDENT sys . setrecursionlimit ( 3000 ) NEW_LINE NUMBER = 10 ** 25 NEW_LINE ans = count_ways ( NUMBER , NUMBER . bit_length ( ) - 1 , 2 ) NEW_LINE return str ( ans ) NEW_LINE DEDENT @ eulerlib . memoize NEW_LINE def count_ways ( number , exponent , repetitions ) : NEW_LINE INDENT if exponent < 0 : NEW_LINE INDENT return 1 if number == 0 else 0 NEW_LINE DEDENT else : NEW_LINE INDENT result = count_ways ( number , exponent - 1 , 2 ) NEW_LINE power = 1 << exponent NEW_LINE upper = power * ( repetitions + 2 ) NEW_LINE if repetitions > 0 and power <= number < upper : NEW_LINE INDENT result += count_ways ( number - power , exponent , repetitions - 1 ) NEW_LINE DEDENT return result NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40317
public final class p204 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p204 ( ) . run ( ) ) ; } public String run ( ) { return Integer . toString ( count ( 0 , 1 ) ) ; } private static long LIMIT = Library . pow ( 10 , 9 ) ; private int [ ] primes = Library . listPrimes ( 100 ) ; private int count ( int primeIndex , long product ) { if ( primeIndex == primes . length ) return product <= LIMIT ? 1 : 0 ; else { int count = 0 ; while ( product <= LIMIT ) { count += count ( primeIndex + 1 , product ) ; product *= primes [ primeIndex ] ; } return count ; } } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT LIMIT = 10 ** 9 NEW_LINE primes = eulerlib . list_primes ( 100 ) NEW_LINE def count ( primeindex , product ) : NEW_LINE INDENT if primeindex == len ( primes ) : NEW_LINE INDENT return 1 if product <= LIMIT else 0 NEW_LINE DEDENT else : NEW_LINE INDENT result = 0 NEW_LINE while product <= LIMIT : NEW_LINE INDENT result += count ( primeindex + 1 , product ) NEW_LINE product *= primes [ primeindex ] NEW_LINE DEDENT return result NEW_LINE DEDENT DEDENT return str ( count ( 0 , 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40318
import java . math . BigInteger ; public final class p057 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p057 ( ) . run ( ) ) ; } private static final int LIMIT = 1000 ; public String run ( ) { BigInteger n = BigInteger . ZERO ; BigInteger d = BigInteger . ONE ; int count = 0 ; for ( int i = 0 ; i < LIMIT ; i ++ ) { BigInteger temp = d . multiply ( BigInteger . valueOf ( 2 ) ) . add ( n ) ; n = d ; d = temp ; if ( n . add ( d ) . toString ( ) . length ( ) > d . toString ( ) . length ( ) ) count ++ ; } return Integer . toString ( count ) ; } }
def compute ( ) : NEW_LINE INDENT LIMIT = 1000 NEW_LINE ans = 0 NEW_LINE numer = 0 NEW_LINE denom = 1 NEW_LINE for _ in range ( LIMIT ) : NEW_LINE INDENT numer , denom = denom , denom * 2 + numer NEW_LINE if len ( str ( numer + denom ) ) > len ( str ( denom ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40319
import java . math . BigInteger ; import java . util . ArrayList ; import java . util . SortedSet ; import java . util . TreeSet ; public final class p119 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p119 ( ) . run ( ) ) ; } private static final int INDEX = 30 ; public String run ( ) { for ( BigInteger limit = BigInteger . ONE ; ; limit = limit . shiftLeft ( 8 ) ) { SortedSet < BigInteger > candidates = new TreeSet < > ( ) ; for ( int k = 2 ; BigInteger . valueOf ( 1 ) . shiftLeft ( k ) . compareTo ( limit ) < 0 ; k ++ ) { for ( int n = 2 ; ; n ++ ) { BigInteger pow = BigInteger . valueOf ( n ) . pow ( k ) ; if ( pow . compareTo ( limit ) >= 0 && pow . toString ( ) . length ( ) * 9 < n ) break ; if ( pow . compareTo ( BigInteger . TEN ) >= 0 && isDigitSumPower ( pow ) ) candidates . add ( pow ) ; } } if ( candidates . size ( ) >= INDEX ) return new ArrayList < > ( candidates ) . get ( INDEX - 1 ) . toString ( ) ; } } private static boolean isDigitSumPower ( BigInteger x ) { int digitSum = digitSum ( x ) ; if ( digitSum == 1 ) return false ; BigInteger base = BigInteger . valueOf ( digitSum ) ; BigInteger pow = base ; while ( pow . compareTo ( x ) < 0 ) pow = pow . multiply ( base ) ; return pow . equals ( x ) ; } private static int digitSum ( BigInteger x ) { if ( x . signum ( ) < 1 ) throw new IllegalArgumentException ( " Only ▁ for ▁ positive ▁ integers " ) ; int sum = 0 ; for ( char c : x . toString ( ) . toCharArray ( ) ) sum += c - '0' ; return sum ; } }
import itertools NEW_LINE def compute ( ) : NEW_LINE INDENT INDEX = 30 NEW_LINE limit = 1 NEW_LINE while True : NEW_LINE INDENT candidates = set ( ) NEW_LINE k = 2 NEW_LINE while ( 1 << k ) < limit : NEW_LINE INDENT for n in itertools . count ( 2 ) : NEW_LINE INDENT pow = n ** k NEW_LINE if pow >= limit and len ( str ( pow ) ) * 9 < n : NEW_LINE INDENT break NEW_LINE DEDENT if pow >= 10 and is_digit_sum_power ( pow ) : NEW_LINE INDENT candidates . add ( pow ) NEW_LINE DEDENT DEDENT k += 1 NEW_LINE DEDENT if len ( candidates ) >= INDEX : NEW_LINE INDENT return str ( sorted ( candidates ) [ INDEX - 1 ] ) NEW_LINE DEDENT limit <<= 8 NEW_LINE DEDENT DEDENT def is_digit_sum_power ( x ) : NEW_LINE INDENT digitsum = sum ( int ( c ) for c in str ( x ) ) NEW_LINE if digitsum == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT pow = digitsum NEW_LINE while pow < x : NEW_LINE INDENT pow *= digitsum NEW_LINE DEDENT return pow == x NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40320
public final class p047 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p047 ( ) . run ( ) ) ; } public String run ( ) { for ( int i = 2 ; ; i ++ ) { if ( has4PrimeFactors ( i + 0 ) && has4PrimeFactors ( i + 1 ) && has4PrimeFactors ( i + 2 ) && has4PrimeFactors ( i + 3 ) ) return Integer . toString ( i ) ; } } private static boolean has4PrimeFactors ( int n ) { return countDistinctPrimeFactors ( n ) == 4 ; } private static int countDistinctPrimeFactors ( int n ) { int count = 0 ; for ( int i = 2 , end = Library . sqrt ( n ) ; i <= end ; i ++ ) { if ( n % i == 0 ) { do n /= i ; while ( n % i == 0 ) ; count ++ ; end = Library . sqrt ( n ) ; } } if ( n > 1 ) count ++ ; return count ; } }
import eulerlib , itertools NEW_LINE def compute ( ) : NEW_LINE INDENT cond = lambda i : all ( ( count_distinct_prime_factors ( i + j ) == 4 ) for j in range ( 4 ) ) NEW_LINE ans = next ( filter ( cond , itertools . count ( ) ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT @ eulerlib . memoize NEW_LINE def count_distinct_prime_factors ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while n > 1 : NEW_LINE INDENT count += 1 NEW_LINE for i in range ( 2 , eulerlib . sqrt ( n ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT while True : NEW_LINE INDENT n //= i NEW_LINE if n % i != 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40321
import java . util . Arrays ; public final class p070 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p070 ( ) . run ( ) ) ; } private static final int LIMIT = Library . pow ( 10 , 7 ) ; public String run ( ) { int minNumer = 1 ; int minDenom = 0 ; int [ ] totients = Library . listTotients ( LIMIT - 1 ) ; for ( int n = 2 ; n < totients . length ; n ++ ) { int tot = totients [ n ] ; if ( ( long ) n * minDenom < ( long ) minNumer * tot && hasSameDigits ( n , tot ) ) { minNumer = n ; minDenom = tot ; } } if ( minDenom == 0 ) throw new RuntimeException ( " Not ▁ found " ) ; return Integer . toString ( minNumer ) ; } private static boolean hasSameDigits ( int x , int y ) { char [ ] xdigits = Integer . toString ( x ) . toCharArray ( ) ; char [ ] ydigits = Integer . toString ( y ) . toCharArray ( ) ; Arrays . sort ( xdigits ) ; Arrays . sort ( ydigits ) ; return Arrays . equals ( xdigits , ydigits ) ; } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT totients = eulerlib . list_totients ( 10 ** 7 - 1 ) NEW_LINE minnumer = 1 NEW_LINE mindenom = 0 NEW_LINE for ( i , tot ) in enumerate ( totients [ 2 : ] , 2 ) : NEW_LINE INDENT if i * mindenom < minnumer * tot and sorted ( str ( i ) ) == sorted ( str ( tot ) ) : NEW_LINE INDENT minnumer = i NEW_LINE mindenom = totients [ i ] NEW_LINE DEDENT DEDENT return str ( minnumer ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40322
public final class p301 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p301 ( ) . run ( ) ) ; } public String run ( ) { int a = 0 ; int b = 1 ; for ( int i = 0 ; i < 32 ; i ++ ) { int c = a + b ; a = b ; b = c ; } return Integer . toString ( a ) ; } }
def compute ( ) : NEW_LINE INDENT a = 0 NEW_LINE b = 1 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT a , b = b , a + b NEW_LINE DEDENT return str ( a ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40323
import java . math . BigInteger ; public final class p162 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p162 ( ) . run ( ) ) ; } public String run ( ) { BigInteger sum = BigInteger . ZERO ; for ( int n = 1 ; n <= 16 ; n ++ ) { sum = sum . add ( bi ( 15 ) . multiply ( bi ( 16 ) . pow ( n - 1 ) ) ) . subtract ( bi ( 43 ) . multiply ( bi ( 15 ) . pow ( n - 1 ) ) ) . add ( bi ( 41 ) . multiply ( bi ( 14 ) . pow ( n - 1 ) ) ) . subtract ( bi ( 13 ) . pow ( n ) ) ; } return sum . toString ( 16 ) . toUpperCase ( ) ; } private static BigInteger bi ( int n ) { return BigInteger . valueOf ( n ) ; } }
def compute ( ) : NEW_LINE INDENT ans = sum ( ( 15 * 16 ** ( n - 1 ) - 43 * 15 ** ( n - 1 ) + 41 * 14 ** ( n - 1 ) - 13 ** n ) for n in range ( 1 , 17 ) ) NEW_LINE return f " { ans : X } " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40324
public final class p171 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p171 ( ) . run ( ) ) ; } private static final int LENGTH = 20 ; private static final int BASE = 10 ; private static final int MODULUS = Library . pow ( 10 , 9 ) ; public String run ( ) { int MAX_SQR_DIGIT_SUM = ( BASE - 1 ) * ( BASE - 1 ) * LENGTH ; long [ ] [ ] sum = new long [ LENGTH + 1 ] [ MAX_SQR_DIGIT_SUM + 1 ] ; long [ ] [ ] count = new long [ LENGTH + 1 ] [ MAX_SQR_DIGIT_SUM + 1 ] ; count [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= LENGTH ; i ++ ) { for ( int j = 0 ; j < BASE ; j ++ ) { for ( int k = 0 ; k + j * j <= MAX_SQR_DIGIT_SUM ; k ++ ) { sum [ i ] [ k + j * j ] = ( sum [ i ] [ k + j * j ] + sum [ i - 1 ] [ k ] + Library . powMod ( BASE , i - 1 , MODULUS ) * j % MODULUS * count [ i - 1 ] [ k ] ) % MODULUS ; count [ i ] [ k + j * j ] = ( count [ i ] [ k + j * j ] + count [ i - 1 ] [ k ] ) % MODULUS ; } } } long s = 0 ; for ( int i = 1 ; i * i <= MAX_SQR_DIGIT_SUM ; i ++ ) s = ( s + sum [ LENGTH ] [ i * i ] ) % MODULUS ; return String . format ( " % 09d " , s ) ; } }
import eulerlib , itertools NEW_LINE def compute ( ) : NEW_LINE INDENT LENGTH = 20 NEW_LINE BASE = 10 NEW_LINE MODULUS = 10 ** 9 NEW_LINE MAX_SQR_DIGIT_SUM = ( BASE - 1 ) ** 2 * LENGTH NEW_LINE sqsum = [ ] NEW_LINE count = [ ] NEW_LINE for i in range ( LENGTH + 1 ) : NEW_LINE INDENT sqsum . append ( [ 0 ] * ( MAX_SQR_DIGIT_SUM + 1 ) ) NEW_LINE count . append ( [ 0 ] * ( MAX_SQR_DIGIT_SUM + 1 ) ) NEW_LINE if i == 0 : NEW_LINE INDENT count [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( BASE ) : NEW_LINE INDENT for k in itertools . count ( ) : NEW_LINE INDENT index = k + j ** 2 NEW_LINE if index > MAX_SQR_DIGIT_SUM : NEW_LINE INDENT break NEW_LINE DEDENT sqsum [ i ] [ index ] = ( sqsum [ i ] [ index ] + sqsum [ i - 1 ] [ k ] + pow ( BASE , i - 1 , MODULUS ) * j * count [ i - 1 ] [ k ] ) % MODULUS NEW_LINE count [ i ] [ index ] = ( count [ i ] [ index ] + count [ i - 1 ] [ k ] ) % MODULUS NEW_LINE DEDENT DEDENT DEDENT DEDENT ans = sum ( sqsum [ LENGTH ] [ i ** 2 ] for i in range ( 1 , eulerlib . sqrt ( MAX_SQR_DIGIT_SUM ) ) ) NEW_LINE return f " { ans % MODULUS : 09 } " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40325
import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; public final class p088 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p088 ( ) . run ( ) ) ; } private static final int LIMIT = 12000 ; private int [ ] minSumProduct ; public String run ( ) { minSumProduct = new int [ LIMIT + 1 ] ; Arrays . fill ( minSumProduct , Integer . MAX_VALUE ) ; for ( int i = 2 ; i <= LIMIT * 2 ; i ++ ) factorize ( i , i , i , 0 , 0 ) ; Set < Integer > items = new HashSet < > ( ) ; for ( int i = 2 ; i < minSumProduct . length ; i ++ ) items . add ( minSumProduct [ i ] ) ; int sum = 0 ; for ( int n : items ) sum += n ; return Integer . toString ( sum ) ; } private void factorize ( int n , int remain , int maxFactor , int sum , int terms ) { if ( remain == 1 ) { if ( sum > n ) throw new AssertionError ( ) ; terms += n - sum ; if ( terms <= LIMIT && n < minSumProduct [ terms ] ) minSumProduct [ terms ] = n ; } else { for ( int i = 2 ; i <= maxFactor ; i ++ ) { if ( remain % i == 0 ) { int factor = i ; factorize ( n , remain / factor , Math . min ( factor , maxFactor ) , sum + factor , terms + 1 ) ; } } } } }
def compute ( ) : NEW_LINE INDENT LIMIT = 12000 NEW_LINE minsumproduct = [ None ] * ( LIMIT + 1 ) NEW_LINE def factorize ( n , remain , maxfactor , sum , terms ) : NEW_LINE INDENT if remain == 1 : NEW_LINE INDENT if sum > n : NEW_LINE INDENT raise AssertionError ( ) NEW_LINE DEDENT terms += n - sum NEW_LINE if terms <= LIMIT and ( minsumproduct [ terms ] is None or n < minsumproduct [ terms ] ) : NEW_LINE INDENT minsumproduct [ terms ] = n NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 2 , maxfactor + 1 ) : NEW_LINE INDENT if remain % i == 0 : NEW_LINE INDENT factor = i NEW_LINE factorize ( n , remain // factor , min ( factor , maxfactor ) , sum + factor , terms + 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( 2 , LIMIT * 2 + 1 ) : NEW_LINE INDENT factorize ( i , i , i , 0 , 0 ) NEW_LINE DEDENT ans = sum ( set ( minsumproduct [ 2 : ] ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40326
import java . math . BigInteger ; public final class p055 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p055 ( ) . run ( ) ) ; } public String run ( ) { int count = 0 ; for ( int i = 0 ; i < 10000 ; i ++ ) { if ( isLychrel ( i ) ) count ++ ; } return Integer . toString ( count ) ; } private static boolean isLychrel ( int n ) { BigInteger temp = BigInteger . valueOf ( n ) ; for ( int i = 0 ; i < 49 ; i ++ ) { temp = temp . add ( new BigInteger ( Library . reverse ( temp . toString ( ) ) ) ) ; if ( Library . isPalindrome ( temp . toString ( ) ) ) return false ; } return true ; } }
def compute ( ) : NEW_LINE INDENT ans = sum ( 1 for i in range ( 10000 ) if is_lychrel ( i ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT def is_lychrel ( n ) : NEW_LINE INDENT for i in range ( 50 ) : NEW_LINE INDENT n += int ( str ( n ) [ : : - 1 ] ) NEW_LINE if str ( n ) == str ( n ) [ : : - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40327
public final class p024 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p024 ( ) . run ( ) ) ; } public String run ( ) { int [ ] array = new int [ 10 ] ; for ( int i = 0 ; i < array . length ; i ++ ) array [ i ] = i ; for ( int i = 0 ; i < 999999 ; i ++ ) { if ( ! Library . nextPermutation ( array ) ) throw new AssertionError ( ) ; } String ans = " " ; for ( int i = 0 ; i < array . length ; i ++ ) ans += array [ i ] ; return ans ; } }
import itertools NEW_LINE def compute ( ) : NEW_LINE INDENT arr = list ( range ( 10 ) ) NEW_LINE temp = itertools . islice ( itertools . permutations ( arr ) , 999999 , None ) NEW_LINE return " " . join ( str ( x ) for x in next ( temp ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40328
public final class p036 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p036 ( ) . run ( ) ) ; } public String run ( ) { long sum = 0 ; for ( int i = 1 ; i < 1000000 ; i ++ ) { if ( Library . isPalindrome ( Integer . toString ( i , 10 ) ) && Library . isPalindrome ( Integer . toString ( i , 2 ) ) ) sum += i ; } return Long . toString ( sum ) ; } }
def compute ( ) : NEW_LINE INDENT ans = sum ( i for i in range ( 1000000 ) if is_decimal_binary_palindrome ( i ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT def is_decimal_binary_palindrome ( n ) : NEW_LINE INDENT s = str ( n ) NEW_LINE if s != s [ : : - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT t = bin ( n ) [ 2 : ] NEW_LINE return t == t [ : : - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40329
public final class p085 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p085 ( ) . run ( ) ) ; } private static final int TARGET = 2000000 ; public String run ( ) { int bestDiff = Integer . MAX_VALUE ; int bestArea = - 1 ; int sqrt = Library . sqrt ( TARGET ) ; for ( int w = 1 ; w <= sqrt ; w ++ ) { for ( int h = 1 ; h <= sqrt ; h ++ ) { int diff = Math . abs ( numberOfRectangles ( w , h ) - TARGET ) ; if ( diff < bestDiff ) { bestDiff = diff ; bestArea = w * h ; } } } return Integer . toString ( bestArea ) ; } private static int numberOfRectangles ( int m , int n ) { return ( m + 1 ) * m * ( n + 1 ) * n / 4 ; } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT TARGET = 2000000 NEW_LINE end = eulerlib . sqrt ( TARGET ) + 1 NEW_LINE gen = ( ( w , h ) for w in range ( 1 , end ) for h in range ( 1 , end ) ) NEW_LINE func = lambda wh : abs ( num_rectangles ( * wh ) - TARGET ) NEW_LINE ans = min ( gen , key = func ) NEW_LINE return str ( ans [ 0 ] * ans [ 1 ] ) NEW_LINE DEDENT def num_rectangles ( m , n ) : NEW_LINE INDENT return ( m + 1 ) * m * ( n + 1 ) * n // 4 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40330
import java . math . BigInteger ; import java . util . HashSet ; import java . util . Set ; public final class p346 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p346 ( ) . run ( ) ) ; } private static final long LIMIT = 1_000_000_000_000L ; public String run ( ) { Set < Long > strongRepunits = new HashSet < > ( ) ; strongRepunits . add ( 1L ) ; for ( int length = 3 ; length <= BigInteger . valueOf ( LIMIT ) . bitLength ( ) ; length ++ ) { middle : for ( int base = 2 ; ; base ++ ) { long value = 0 ; for ( int i = 0 ; i < length ; i ++ ) { if ( Long . MAX_VALUE / base < value ) break middle ; value *= base ; if ( value + 1 < value ) break middle ; value ++ ; } if ( value >= LIMIT ) break ; strongRepunits . add ( value ) ; } } long sum = 0 ; for ( long x : strongRepunits ) { if ( sum + x < sum ) throw new ArithmeticException ( " Overflow " ) ; sum += x ; } return Long . toString ( sum ) ; } }
import itertools NEW_LINE def compute ( ) : NEW_LINE INDENT LIMIT = 10 ** 12 NEW_LINE strongrepunits = { 1 } NEW_LINE for length in range ( 3 , LIMIT . bit_length ( ) + 1 ) : NEW_LINE INDENT for base in itertools . count ( 2 ) : NEW_LINE INDENT value = ( base ** length - 1 ) // ( base - 1 ) NEW_LINE if value >= LIMIT : NEW_LINE INDENT break NEW_LINE DEDENT strongrepunits . add ( value ) NEW_LINE DEDENT DEDENT ans = sum ( strongrepunits ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40331
public final class p035 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p035 ( ) . run ( ) ) ; } private static final int LIMIT = Library . pow ( 10 , 6 ) ; private boolean [ ] isPrime = Library . listPrimality ( LIMIT - 1 ) ; public String run ( ) { int count = 0 ; for ( int i = 0 ; i < isPrime . length ; i ++ ) { if ( isCircularPrime ( i ) ) count ++ ; } return Integer . toString ( count ) ; } private boolean isCircularPrime ( int n ) { String s = Integer . toString ( n ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! isPrime [ Integer . parseInt ( s . substring ( i ) + s . substring ( 0 , i ) ) ] ) return false ; } return true ; } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT isprime = eulerlib . list_primality ( 999999 ) NEW_LINE def is_circular_prime ( n ) : NEW_LINE INDENT s = str ( n ) NEW_LINE return all ( isprime [ int ( s [ i : ] + s [ : i ] ) ] for i in range ( len ( s ) ) ) NEW_LINE DEDENT ans = sum ( 1 for i in range ( len ( isprime ) ) if is_circular_prime ( i ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40332
import java . math . BigInteger ; import java . util . Arrays ; public final class p104 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p104 ( ) . run ( ) ) ; } public String run ( ) { int i = 0 ; int a = 0 ; int b = 1 ; while ( ! isFound ( i , a ) ) { int c = ( a + b ) % 1000000000 ; a = b ; b = c ; i ++ ; } return Integer . toString ( i ) ; } private static boolean isFound ( int n , int fibMod ) { if ( ! isPandigital ( Integer . toString ( fibMod ) ) ) return false ; BigInteger fib = fibonacci ( n ) [ 0 ] ; if ( fib . mod ( BigInteger . valueOf ( 1000000000 ) ) . intValue ( ) != fibMod ) throw new AssertionError ( ) ; return isPandigital ( leading9Digits ( fib ) ) ; } private static String leading9Digits ( BigInteger x ) { int log10 = ( x . bitLength ( ) - 1 ) * 3 / 10 ; x = x . divide ( BigInteger . TEN . pow ( Math . max ( log10 + 1 - 9 , 0 ) ) ) ; return x . toString ( ) . substring ( 0 , 9 ) ; } private static boolean isPandigital ( String s ) { if ( s . length ( ) != 9 ) return false ; char [ ] temp = s . toCharArray ( ) ; Arrays . sort ( temp ) ; return new String ( temp ) . equals ( "123456789" ) ; } private static BigInteger [ ] fibonacci ( int n ) { if ( n < 0 ) throw new IllegalArgumentException ( ) ; else if ( n == 0 ) return new BigInteger [ ] { BigInteger . ZERO , BigInteger . ONE } ; else { BigInteger [ ] ab = fibonacci ( n / 2 ) ; BigInteger a = ab [ 0 ] ; BigInteger b = ab [ 1 ] ; BigInteger c = a . multiply ( b . shiftLeft ( 1 ) . subtract ( a ) ) ; BigInteger d = a . multiply ( a ) . add ( b . multiply ( b ) ) ; if ( n % 2 == 0 ) return new BigInteger [ ] { c , d } ; else return new BigInteger [ ] { d , c . add ( d ) } ; } } }
import itertools NEW_LINE def compute ( ) : NEW_LINE INDENT MOD = 10 ** 9 NEW_LINE a = 0 NEW_LINE b = 1 NEW_LINE for i in itertools . count ( ) : NEW_LINE INDENT if " " . join ( sorted ( str ( a ) ) ) == "123456789" : NEW_LINE INDENT f = fibonacci ( i ) [ 0 ] NEW_LINE if " " . join ( sorted ( str ( f ) [ : 9 ] ) ) == "123456789" : NEW_LINE INDENT return str ( i ) NEW_LINE DEDENT DEDENT a , b = b , ( a + b ) % MOD NEW_LINE DEDENT return str ( ans ) NEW_LINE DEDENT def fibonacci ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return ( 0 , 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT a , b = fibonacci ( n // 2 ) NEW_LINE c = a * ( b * 2 - a ) NEW_LINE d = a * a + b * b NEW_LINE if n % 2 == 0 : NEW_LINE INDENT return ( c , d ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( d , c + d ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40333
public final class p206 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p206 ( ) . run ( ) ) ; } public String run ( ) { long n = 1000000000 ; int [ ] ndigits = new int [ 10 ] ; int [ ] n2digits = new int [ 19 ] ; long temp = n ; for ( int i = 0 ; i < ndigits . length ; i ++ , temp /= 10 ) ndigits [ i ] = ( int ) ( temp % 10 ) ; temp = n * n ; for ( int i = 0 ; i < n2digits . length ; i ++ , temp /= 10 ) n2digits [ i ] = ( int ) ( temp % 10 ) ; while ( ! isConcealedSquare ( n2digits ) ) { add20n ( ndigits , n2digits ) ; add10Pow ( n2digits , 2 ) ; n += 10 ; add10Pow ( ndigits , 1 ) ; } return Long . toString ( n ) ; } private static boolean isConcealedSquare ( int [ ] n ) { for ( int i = 1 ; i <= 9 ; i ++ ) { if ( n [ 20 - i * 2 ] != i ) return false ; } return n [ 0 ] == 0 ; } private static void add10Pow ( int [ ] n , int i ) { while ( n [ i ] == 9 ) { n [ i ] = 0 ; i ++ ; } n [ i ] ++ ; } private static void add20n ( int [ ] n , int [ ] n2 ) { int carry = 0 ; int i ; for ( i = 0 ; i < n . length ; i ++ ) { int sum = n [ i ] * 2 + n2 [ i + 1 ] + carry ; n2 [ i + 1 ] = sum % 10 ; carry = sum / 10 ; } for ( i ++ ; carry > 0 ; i ++ ) { int sum = n2 [ i ] + carry ; n2 [ i ] = sum % 10 ; carry = sum / 10 ; } } }
def compute ( ) : NEW_LINE INDENT n = 1000000000 NEW_LINE ndigits = [ 0 ] * 10 NEW_LINE temp = n NEW_LINE for i in range ( len ( ndigits ) ) : NEW_LINE INDENT ndigits [ i ] = temp % 10 NEW_LINE temp //= 10 NEW_LINE DEDENT n2digits = [ 0 ] * 19 NEW_LINE temp = n * n NEW_LINE for i in range ( len ( n2digits ) ) : NEW_LINE INDENT n2digits [ i ] = temp % 10 NEW_LINE temp //= 10 NEW_LINE DEDENT while not is_concealed_square ( n2digits ) : NEW_LINE INDENT add_20n ( ndigits , n2digits ) NEW_LINE add_10pow ( n2digits , 2 ) NEW_LINE n += 10 NEW_LINE add_10pow ( ndigits , 1 ) NEW_LINE DEDENT return str ( n ) NEW_LINE DEDENT def is_concealed_square ( n ) : NEW_LINE INDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT if n [ 20 - i * 2 ] != i : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return n [ 0 ] == 0 NEW_LINE DEDENT def add_10pow ( n , i ) : NEW_LINE INDENT while n [ i ] == 9 : NEW_LINE INDENT n [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT n [ i ] += 1 NEW_LINE DEDENT def add_20n ( n , n2 ) : NEW_LINE INDENT carry = 0 NEW_LINE i = 0 NEW_LINE while i < len ( n ) : NEW_LINE INDENT sum = n [ i ] * 2 + n2 [ i + 1 ] + carry NEW_LINE n2 [ i + 1 ] = sum % 10 NEW_LINE carry = sum // 10 NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE while carry > 0 : NEW_LINE INDENT sum = n2 [ i ] + carry NEW_LINE n2 [ i ] = sum % 10 NEW_LINE carry = sum // 10 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40334
public final class p077 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p077 ( ) . run ( ) ) ; } private static final int TARGET = 5000 ; public String run ( ) { for ( int limit = 1 ; ; limit *= 2 ) { int result = search ( limit , TARGET ) ; if ( result != - 1 ) return Integer . toString ( result ) ; } } private static int search ( int limit , int target ) { int [ ] partitions = new int [ limit ] ; partitions [ 0 ] = 1 ; for ( int i = 0 ; i < partitions . length ; i ++ ) { if ( ! Library . isPrime ( i ) ) continue ; for ( int j = i ; j < partitions . length ; j ++ ) partitions [ j ] += partitions [ j - i ] ; } for ( int i = 0 ; i < limit ; i ++ ) { if ( partitions [ i ] > target ) return i ; } return - 1 ; } }
import eulerlib , itertools NEW_LINE def compute ( ) : NEW_LINE INDENT cond = lambda n : num_prime_sum_ways ( n ) > 5000 NEW_LINE ans = next ( filter ( cond , itertools . count ( 2 ) ) ) NEW_LINE return str ( ans ) NEW_LINE DEDENT primes = [ 2 ] NEW_LINE def num_prime_sum_ways ( n ) : NEW_LINE INDENT for i in range ( primes [ - 1 ] + 1 , n + 1 ) : NEW_LINE INDENT if eulerlib . is_prime ( i ) : NEW_LINE INDENT primes . append ( i ) NEW_LINE DEDENT DEDENT ways = [ 1 ] + [ 0 ] * n NEW_LINE for p in primes : NEW_LINE INDENT for i in range ( n + 1 - p ) : NEW_LINE INDENT ways [ i + p ] += ways [ i ] NEW_LINE DEDENT DEDENT return ways [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40335
public final class p116 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p116 ( ) . run ( ) ) ; } private static final int LENGTH = 50 ; public String run ( ) { return Long . toString ( countWays ( LENGTH , 2 ) + countWays ( LENGTH , 3 ) + countWays ( LENGTH , 4 ) ) ; } private static long countWays ( int length , int m ) { long [ ] ways = new long [ length + 1 ] ; ways [ 0 ] = 1 ; for ( int n = 1 ; n <= length ; n ++ ) { ways [ n ] += ways [ n - 1 ] ; if ( n >= m ) ways [ n ] += ways [ n - m ] ; } return ways [ length ] - 1 ; } }
def compute ( ) : NEW_LINE INDENT LENGTH = 50 NEW_LINE return str ( sum ( count_ways ( LENGTH , i ) for i in range ( 2 , 5 ) ) ) NEW_LINE DEDENT def count_ways ( length , m ) : NEW_LINE INDENT ways = [ 1 ] + [ 0 ] * length NEW_LINE for n in range ( 1 , len ( ways ) ) : NEW_LINE INDENT ways [ n ] += ways [ n - 1 ] NEW_LINE if n >= m : NEW_LINE INDENT ways [ n ] += ways [ n - m ] NEW_LINE DEDENT DEDENT return ways [ - 1 ] - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40336
import java . math . BigInteger ; public final class p100 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p100 ( ) . run ( ) ) ; } public String run ( ) { BigInteger x0 = BigInteger . valueOf ( 3 ) ; BigInteger y0 = BigInteger . valueOf ( 1 ) ; BigInteger x = x0 ; BigInteger y = y0 ; while ( true ) { BigInteger sqrt = Library . sqrt ( y . multiply ( y ) . multiply ( BigInteger . valueOf ( 8 ) ) . add ( BigInteger . ONE ) ) ; if ( sqrt . testBit ( 0 ) ) { BigInteger blue = sqrt . add ( BigInteger . ONE ) . divide ( BigInteger . valueOf ( 2 ) ) . add ( y ) ; if ( blue . add ( y ) . compareTo ( BigInteger . TEN . pow ( 12 ) ) > 0 ) return blue . toString ( ) ; } BigInteger nextx = x . multiply ( x0 ) . add ( y . multiply ( y0 ) . multiply ( BigInteger . valueOf ( 8 ) ) ) ; BigInteger nexty = x . multiply ( y0 ) . add ( y . multiply ( x0 ) ) ; x = nextx ; y = nexty ; } } }
import eulerlib NEW_LINE def compute ( ) : NEW_LINE INDENT x0 = 3 NEW_LINE y0 = 1 NEW_LINE x = x0 NEW_LINE y = y0 NEW_LINE while True : NEW_LINE INDENT sqrt = eulerlib . sqrt ( y ** 2 * 8 + 1 ) NEW_LINE if sqrt % 2 == 1 : NEW_LINE INDENT blue = ( sqrt + 1 ) // 2 + y NEW_LINE if blue + y > 10 ** 12 : NEW_LINE INDENT return str ( blue ) NEW_LINE DEDENT DEDENT nextx = x * x0 + y * y0 * 8 NEW_LINE nexty = x * y0 + y * x0 NEW_LINE x = nextx NEW_LINE y = nexty NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40337
public final class p222 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p222 ( ) . run ( ) ) ; } public String run ( ) { sphereRadii = new double [ 21 ] ; for ( int i = 0 ; i < sphereRadii . length ; i ++ ) sphereRadii [ i ] = ( i + 30 ) * 1000 ; minLength = new double [ sphereRadii . length ] [ 1 << sphereRadii . length ] ; double min = Double . POSITIVE_INFINITY ; for ( int i = 0 ; i < sphereRadii . length ; i ++ ) min = Math . min ( findMinimumLength ( i , ( 1 << sphereRadii . length ) - 1 ) + sphereRadii [ i ] , min ) ; return Long . toString ( Math . round ( min ) ) ; } private double [ ] sphereRadii ; private double [ ] [ ] minLength ; private double findMinimumLength ( int currentSphereIndex , int setOfSpheres ) { if ( ( setOfSpheres & ( 1 << currentSphereIndex ) ) == 0 ) throw new IllegalArgumentException ( ) ; if ( minLength [ currentSphereIndex ] [ setOfSpheres ] == 0 ) { double result ; if ( Integer . bitCount ( setOfSpheres ) == 1 ) result = sphereRadii [ currentSphereIndex ] ; else { result = Double . POSITIVE_INFINITY ; int newSetOfSpheres = setOfSpheres ^ ( 1 << currentSphereIndex ) ; for ( int i = 0 ; i < sphereRadii . length ; i ++ ) { if ( ( newSetOfSpheres & ( 1 << i ) ) == 0 ) continue ; double temp = Math . sqrt ( ( sphereRadii [ i ] + sphereRadii [ currentSphereIndex ] - 50000 ) * 200000 ) ; temp += findMinimumLength ( i , newSetOfSpheres ) ; result = Math . min ( temp , result ) ; } } minLength [ currentSphereIndex ] [ setOfSpheres ] = result ; } return minLength [ currentSphereIndex ] [ setOfSpheres ] ; } }
import eulerlib , math NEW_LINE def compute ( ) : NEW_LINE INDENT NUM_SPHERES = 21 NEW_LINE sphereradii = [ ( i + 30 ) * 1000 for i in range ( NUM_SPHERES ) ] NEW_LINE minlength = [ [ None ] * ( 2 ** NUM_SPHERES ) for _ in range ( NUM_SPHERES ) ] NEW_LINE def find_minimum_length ( currentsphereindex , setofspheres ) : NEW_LINE INDENT if setofspheres & ( 1 << currentsphereindex ) == 0 : NEW_LINE INDENT raise ValueError ( ) NEW_LINE DEDENT if minlength [ currentsphereindex ] [ setofspheres ] is None : NEW_LINE INDENT if eulerlib . popcount ( setofspheres ) == 1 : NEW_LINE INDENT result = sphereradii [ currentsphereindex ] NEW_LINE DEDENT else : NEW_LINE INDENT result = float ( " inf " ) NEW_LINE newsetofspheres = setofspheres ^ ( 1 << currentsphereindex ) NEW_LINE for i in range ( NUM_SPHERES ) : NEW_LINE INDENT if newsetofspheres & ( 1 << i ) == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT temp = math . sqrt ( ( sphereradii [ i ] + sphereradii [ currentsphereindex ] - 50000 ) * 200000 ) NEW_LINE temp += find_minimum_length ( i , newsetofspheres ) NEW_LINE result = min ( temp , result ) NEW_LINE DEDENT DEDENT minlength [ currentsphereindex ] [ setofspheres ] = result NEW_LINE DEDENT return minlength [ currentsphereindex ] [ setofspheres ] NEW_LINE DEDENT ans = min ( ( find_minimum_length ( i , ( 1 << NUM_SPHERES ) - 1 ) + sphereradii [ i ] ) for i in range ( NUM_SPHERES ) ) NEW_LINE return str ( int ( round ( ans ) ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40338
import java . util . HashSet ; import java . util . Set ; public final class p074 implements EulerSolution { public static void main ( String [ ] args ) { System . out . println ( new p074 ( ) . run ( ) ) ; } private static final int LIMIT = Library . pow ( 10 , 6 ) ; public String run ( ) { int count = 0 ; for ( int i = 0 ; i < LIMIT ; i ++ ) { if ( getChainLength ( i ) == 60 ) count ++ ; } return Integer . toString ( count ) ; } private static int getChainLength ( int n ) { Set < Integer > seen = new HashSet < > ( ) ; while ( true ) { if ( ! seen . add ( n ) ) return seen . size ( ) ; n = factorialize ( n ) ; } } private static int [ ] FACTORIAL = { 1 , 1 , 2 , 6 , 24 , 120 , 720 , 5040 , 40320 , 362880 } ; private static int factorialize ( int n ) { int sum = 0 ; for ( ; n != 0 ; n /= 10 ) sum += FACTORIAL [ n % 10 ] ; return sum ; } }
import math NEW_LINE def compute ( ) : NEW_LINE INDENT LIMIT = 10 ** 6 NEW_LINE ans = sum ( 1 for i in range ( LIMIT ) if get_chain_length ( i ) == 60 ) NEW_LINE return str ( ans ) NEW_LINE DEDENT def get_chain_length ( n ) : NEW_LINE INDENT seen = set ( ) NEW_LINE while True : NEW_LINE INDENT seen . add ( n ) NEW_LINE n = factorialize ( n ) NEW_LINE if n in seen : NEW_LINE INDENT return len ( seen ) NEW_LINE DEDENT DEDENT DEDENT def factorialize ( n ) : NEW_LINE INDENT result = 0 NEW_LINE while n != 0 : NEW_LINE INDENT result += FACTORIAL [ n % 10 ] NEW_LINE n //= 10 NEW_LINE DEDENT return result NEW_LINE DEDENT FACTORIAL = [ math . factorial ( i ) for i in range ( 10 ) ] NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( compute ( ) ) NEW_LINE DEDENT
T40339
class Solution { private TreeNode ans ; public Solution ( ) { this . ans = null ; } private boolean recurseTree ( TreeNode currentNode , TreeNode p , TreeNode q ) { if ( currentNode == null ) { return false ; } int left = this . recurseTree ( currentNode . left , p , q ) ? 1 : 0 ; int right = this . recurseTree ( currentNode . right , p , q ) ? 1 : 0 ; int mid = ( currentNode == p || currentNode == q ) ? 1 : 0 ; if ( mid + left + right >= 2 ) { this . ans = currentNode ; } return ( mid + left + right > 0 ) ; } public TreeNode lowestCommonAncestor ( TreeNode root , TreeNode p , TreeNode q ) { this . recurseTree ( root , p , q ) ; return this . ans ; } }
class Solution ( object ) : NEW_LINE INDENT def lowestCommonAncestor ( self , root , p , q ) : NEW_LINE INDENT stack = [ root ] NEW_LINE parent = { root : None } NEW_LINE while p not in parent or q not in parent : NEW_LINE INDENT node = stack . pop ( ) NEW_LINE if node . left : NEW_LINE INDENT parent [ node . left ] = node NEW_LINE stack . append ( node . left ) NEW_LINE DEDENT if node . right : NEW_LINE INDENT parent [ node . right ] = node NEW_LINE stack . append ( node . right ) NEW_LINE DEDENT DEDENT ancestors = set ( ) NEW_LINE while p : NEW_LINE INDENT ancestors . add ( p ) NEW_LINE p = parent [ p ] NEW_LINE DEDENT while q not in ancestors : NEW_LINE INDENT q = parent [ q ] NEW_LINE DEDENT return q NEW_LINE DEDENT DEDENT
T40340
public class Solution { public int findRadius ( int [ ] houses , int [ ] heaters ) { Arrays . sort ( heaters ) ; int result = Integer . MIN_VALUE ; for ( int house : houses ) { int index = Arrays . binarySearch ( heaters , house ) ; if ( index < 0 ) index = - ( index + 1 ) ; int dist1 = index - 1 >= 0 ? house - heaters [ index - 1 ] : Integer . MAX_VALUE ; int dist2 = index < heaters . length ? heaters [ index ] - house : Integer . MAX_VALUE ; result = Math . max ( result , Math . min ( dist1 , dist2 ) ) ; } return result ; } }
class Solution ( object ) : NEW_LINE INDENT def findRadius ( self , houses , heaters ) : NEW_LINE INDENT heaters = sorted ( heaters ) + [ float ( ' inf ' ) ] NEW_LINE i = r = 0 NEW_LINE for x in sorted ( houses ) : NEW_LINE INDENT while x >= sum ( heaters [ i : i + 2 ] ) / 2. : NEW_LINE INDENT i += 1 NEW_LINE DEDENT r = max ( r , abs ( heaters [ i ] - x ) ) NEW_LINE DEDENT return r NEW_LINE DEDENT DEDENT
T40341
class Solution { private class LargerNumberComparator implements Comparator < String > { @ Override public int compare ( String a , String b ) { String order1 = a + b ; String order2 = b + a ; return order2 . compareTo ( order1 ) ; } } public String largestNumber ( int [ ] nums ) { String [ ] asStrs = new String [ nums . length ] ; for ( int i = 0 ; i < nums . length ; i ++ ) { asStrs [ i ] = String . valueOf ( nums [ i ] ) ; } Arrays . sort ( asStrs , new LargerNumberComparator ( ) ) ; if ( asStrs [ 0 ] . equals ( "0" ) ) { return "0" ; } String largestNumberStr = new String ( ) ; for ( String numAsStr : asStrs ) { largestNumberStr += numAsStr ; } return largestNumberStr ; } }
class LargerNumKey ( str ) : NEW_LINE INDENT def __lt__ ( x , y ) : NEW_LINE INDENT return x + y > y + x NEW_LINE DEDENT DEDENT class Solution : NEW_LINE INDENT def largestNumber ( self , nums ) : NEW_LINE INDENT largest_num = ' ' . join ( sorted ( map ( str , nums ) , key = LargerNumKey ) ) NEW_LINE return '0' if largest_num [ 0 ] == '0' else largest_num NEW_LINE DEDENT DEDENT
T40342
class Solution { public int largestPalindrome ( int n ) { if ( n == 1 ) { return 9 ; } int upperBound = ( int ) Math . pow ( 10 , n ) - 1 , lowerBound = upperBound / 10 ; long maxNumber = ( long ) upperBound * ( long ) upperBound ; int firstHalf = ( int ) ( maxNumber / ( long ) Math . pow ( 10 , n ) ) ; boolean palindromFound = false ; long palindrom = 0 ; while ( ! palindromFound ) { palindrom = createPalindrom ( firstHalf ) ; for ( long i = upperBound ; upperBound > lowerBound ; i -- ) { if ( palindrom / i > maxNumber || i * i < palindrom ) { break ; } if ( palindrom % i == 0 ) { palindromFound = true ; break ; } } firstHalf -- ; } return ( int ) ( palindrom % 1337 ) ; } private long createPalindrom ( long num ) { String str = num + new StringBuilder ( ) . append ( num ) . reverse ( ) . toString ( ) ; return Long . parseLong ( str ) ; } }
class Solution ( object ) : NEW_LINE INDENT def largestPalindrome ( self , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 9 NEW_LINE DEDENT for a in xrange ( 2 , 9 * 10 ** ( n - 1 ) ) : NEW_LINE INDENT hi = ( 10 ** n ) - a NEW_LINE lo = int ( str ( hi ) [ : : - 1 ] ) NEW_LINE if a ** 2 - 4 * lo < 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if ( a ** 2 - 4 * lo ) ** .5 == int ( ( a ** 2 - 4 * lo ) ** .5 ) : NEW_LINE INDENT return ( lo + 10 ** n * ( 10 ** n - a ) ) % 1337 NEW_LINE DEDENT DEDENT DEDENT DEDENT
T40343
class Solution { public int binaryGap ( int N ) { int last = - 1 , ans = 0 ; for ( int i = 0 ; i < 32 ; ++ i ) if ( ( ( N >> i ) & 1 ) > 0 ) { if ( last >= 0 ) ans = Math . max ( ans , i - last ) ; last = i ; } return ans ; } }
class Solution : NEW_LINE INDENT def binaryGap ( self , n : int ) -> int : NEW_LINE INDENT current = 1 NEW_LINE last1 = - 1 NEW_LINE out = 0 NEW_LINE while n > 0 : NEW_LINE INDENT if n % 2 == 1 : NEW_LINE INDENT if last1 >= 1 : NEW_LINE INDENT out = max ( out , current - last1 ) NEW_LINE DEDENT last1 = current NEW_LINE DEDENT current += 1 NEW_LINE n = n // 2 NEW_LINE DEDENT return out NEW_LINE DEDENT DEDENT
T40344
class Solution { public int [ ] anagramMappings ( int [ ] A , int [ ] B ) { int [ ] ans = new int [ A . length ] ; HashMap < Integer , Integer > valIndex = new HashMap < > ( ) ; for ( int i = 0 ; i < B . length ; i ++ ) valIndex . put ( B [ i ] , i ) ; for ( int i = 0 ; i < A . length ; i ++ ) ans [ i ] = valIndex . get ( A [ i ] ) ; return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def anagramMappings ( self , A , B ) : NEW_LINE INDENT val_index = { } NEW_LINE ans = [ ] NEW_LINE for i , n in enumerate ( B ) : NEW_LINE INDENT val_index [ n ] = i NEW_LINE DEDENT for n in A : NEW_LINE INDENT ans . append ( val_index [ n ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT
T40345
public class Solution { public String addStrings ( String num1 , String num2 ) { StringBuilder sb = new StringBuilder ( ) ; int carry = 0 ; for ( int i = num1 . length ( ) - 1 , j = num2 . length ( ) - 1 ; i >= 0 || j >= 0 || carry == 1 ; i -- , j -- ) { int x = i < 0 ? 0 : num1 . charAt ( i ) - '0' ; int y = j < 0 ? 0 : num2 . charAt ( j ) - '0' ; sb . append ( ( x + y + carry ) % 10 ) ; carry = ( x + y + carry ) / 10 ; } return sb . reverse ( ) . toString ( ) ; } }
class Solution ( object ) : NEW_LINE INDENT def addStrings ( self , num1 , num2 ) : NEW_LINE INDENT res = [ ] NEW_LINE pos1 = len ( num1 ) - 1 NEW_LINE pos2 = len ( num2 ) - 1 NEW_LINE carry = 0 NEW_LINE while pos1 >= 0 or pos2 >= 0 or carry == 1 : NEW_LINE INDENT digit1 = digit2 = 0 NEW_LINE if pos1 >= 0 : NEW_LINE INDENT digit1 = ord ( num1 [ pos1 ] ) - ord ( '0' ) NEW_LINE DEDENT if pos2 >= 0 : NEW_LINE INDENT digit2 = ord ( num2 [ pos2 ] ) - ord ( '0' ) NEW_LINE DEDENT res . append ( str ( ( digit1 + digit2 + carry ) % 10 ) ) NEW_LINE carry = ( digit1 + digit2 + carry ) / 10 NEW_LINE pos1 -= 1 NEW_LINE pos2 -= 1 NEW_LINE DEDENT return ' ' . join ( res [ : : - 1 ] ) NEW_LINE DEDENT DEDENT
T40346
public class Solution { public int subarraySum ( int [ ] nums , int k ) { int count = 0 , sum = 0 ; HashMap < Integer , Integer > map = new HashMap < > ( ) ; map . put ( 0 , 1 ) ; for ( int i = 0 ; i < nums . length ; i ++ ) { sum += nums [ i ] ; if ( map . containsKey ( sum - k ) ) count += map . get ( sum - k ) ; map . put ( sum , map . getOrDefault ( sum , 0 ) + 1 ) ; } return count ; } }
class Solution ( object ) : NEW_LINE INDENT def subarraySum ( self , nums , k ) : NEW_LINE INDENT sum_map = { } NEW_LINE sum_map [ 0 ] = 1 NEW_LINE count = curr_sum = 0 NEW_LINE for num in nums : NEW_LINE INDENT curr_sum += num NEW_LINE count += sum_map . get ( curr_sum - k , 0 ) NEW_LINE sum_map [ curr_sum ] = sum_map . get ( curr_sum , 0 ) + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT DEDENT
T40347
class Solution { public int findShortestSubArray ( int [ ] nums ) { Map < Integer , Integer > left = new HashMap ( ) , right = new HashMap ( ) , count = new HashMap ( ) ; for ( int i = 0 ; i < nums . length ; i ++ ) { int x = nums [ i ] ; if ( left . get ( x ) == null ) left . put ( x , i ) ; right . put ( x , i ) ; count . put ( x , count . getOrDefault ( x , 0 ) + 1 ) ; } int ans = nums . length ; int degree = Collections . max ( count . values ( ) ) ; for ( int x : count . keySet ( ) ) { if ( count . get ( x ) == degree ) { ans = Math . min ( ans , right . get ( x ) - left . get ( x ) + 1 ) ; } } return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def findShortestSubArray ( self , nums ) : NEW_LINE INDENT left , right , count = { } , { } , { } NEW_LINE for i , x in enumerate ( nums ) : NEW_LINE INDENT if x not in left : left [ x ] = i NEW_LINE right [ x ] = i NEW_LINE count [ x ] = count . get ( x , 0 ) + 1 NEW_LINE DEDENT ans = len ( nums ) NEW_LINE degree = max ( count . values ( ) ) NEW_LINE for x in count : NEW_LINE INDENT if count [ x ] == degree : NEW_LINE INDENT ans = min ( ans , right [ x ] - left [ x ] + 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT DEDENT
T40348
public class Solution { public int maximumProduct ( int [ ] nums ) { int min1 = Integer . MAX_VALUE , min2 = Integer . MAX_VALUE ; int max1 = Integer . MIN_VALUE , max2 = Integer . MIN_VALUE , max3 = Integer . MIN_VALUE ; for ( int n : nums ) { if ( n <= min1 ) { min2 = min1 ; min1 = n ; } else if ( n <= min2 ) { min2 = n ; } if ( n >= max1 ) { max3 = max2 ; max2 = max1 ; max1 = n ; } else if ( n >= max2 ) { max3 = max2 ; max2 = n ; } else if ( n >= max3 ) { max3 = n ; } } return Math . max ( min1 * min2 * max1 , max1 * max2 * max3 ) ; } }
class Solution ( object ) : NEW_LINE INDENT def maximumProduct ( self , nums ) : NEW_LINE INDENT min1 = min2 = float ( ' inf ' ) NEW_LINE max1 = max2 = max3 = float ( ' - inf ' ) NEW_LINE for num in nums : NEW_LINE INDENT if num <= min1 : NEW_LINE INDENT min2 = min1 NEW_LINE min1 = num NEW_LINE DEDENT elif num <= min2 : NEW_LINE INDENT min2 = num NEW_LINE DEDENT if num >= max1 : NEW_LINE INDENT max3 = max2 NEW_LINE max2 = max1 NEW_LINE max1 = num NEW_LINE DEDENT elif num >= max2 : NEW_LINE INDENT max3 = max2 NEW_LINE max2 = num NEW_LINE DEDENT elif num >= max3 : NEW_LINE INDENT max3 = num NEW_LINE DEDENT DEDENT return max ( min1 * min2 * max1 , max1 * max2 * max3 ) NEW_LINE DEDENT DEDENT
T40349
public class Solution { public TreeNode constructMaximumBinaryTree ( int [ ] nums ) { return construct ( nums , 0 , nums . length ) ; } public TreeNode construct ( int [ ] nums , int l , int r ) { if ( l == r ) return null ; int max_i = max ( nums , l , r ) ; TreeNode root = new TreeNode ( nums [ max_i ] ) ; root . left = construct ( nums , l , max_i ) ; root . right = construct ( nums , max_i + 1 , r ) ; return root ; } public int max ( int [ ] nums , int l , int r ) { int max_i = l ; for ( int i = l ; i < r ; i ++ ) { if ( nums [ max_i ] < nums [ i ] ) max_i = i ; } return max_i ; } }
class Solution ( object ) : NEW_LINE INDENT def constructMaximumBinaryTree ( self , nums ) : NEW_LINE INDENT if nums is None or len ( nums ) == 0 : NEW_LINE INDENT return None NEW_LINE DEDENT max_index , max_value = 0 , 0 NEW_LINE for i , value in enumerate ( nums ) : NEW_LINE INDENT if value >= max_value : NEW_LINE INDENT max_value = value NEW_LINE max_index = i NEW_LINE DEDENT DEDENT root = TreeNode ( max_value ) NEW_LINE root . left = self . constructMaximumBinaryTree ( nums [ : max_index ] ) NEW_LINE root . right = self . constructMaximumBinaryTree ( nums [ max_index + 1 : ] ) NEW_LINE return root NEW_LINE DEDENT DEDENT
T40350
class Solution { public int firstUniqChar ( String s ) { int freq [ ] = new int [ 26 ] ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) freq [ s . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( freq [ s . charAt ( i ) - ' a ' ] == 1 ) return i ; return - 1 ; } }
class Solution ( object ) : NEW_LINE INDENT def firstUniqChar ( self , s ) : NEW_LINE INDENT count_map = { } NEW_LINE for c in s : NEW_LINE INDENT count_map [ c ] = count_map . get ( c , 0 ) + 1 NEW_LINE DEDENT for i , c in enumerate ( s ) : NEW_LINE INDENT if count_map [ c ] == 1 : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT DEDENT
T40351
class Solution { public boolean isPalindromeRange ( String s , int i , int j ) { for ( int k = i ; k <= i + ( j - i ) / 2 ; k ++ ) { if ( s . charAt ( k ) != s . charAt ( j - k + i ) ) return false ; } return true ; } public boolean validPalindrome ( String s ) { for ( int i = 0 ; i < s . length ( ) / 2 ; i ++ ) { if ( s . charAt ( i ) != s . charAt ( s . length ( ) - 1 - i ) ) { int j = s . length ( ) - 1 - i ; return ( isPalindromeRange ( s , i + 1 , j ) || isPalindromeRange ( s , i , j - 1 ) ) ; } } return true ; } }
class Solution ( object ) : NEW_LINE INDENT def validPalindrome ( self , s ) : NEW_LINE INDENT return self . validPalindromeHelper ( s , 0 , len ( s ) - 1 , 1 ) NEW_LINE DEDENT def validPalindromeHelper ( self , s , left , right , budget ) : NEW_LINE INDENT while left < len ( s ) and right >= 0 and left <= right and s [ left ] == s [ right ] : NEW_LINE INDENT left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT if left >= len ( s ) or right < 0 or left >= right : NEW_LINE INDENT return True NEW_LINE DEDENT if budget == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT budget -= 1 NEW_LINE return self . validPalindromeHelper ( s , left + 1 , right , budget ) or self . validPalindromeHelper ( s , left , right - 1 , budget ) NEW_LINE DEDENT DEDENT
T40352
class Solution { private List < Integer > memo ; public Solution ( ) { memo = new ArrayList ( ) ; memo . add ( 0 ) ; memo . add ( 1 ) ; } public int fib ( int N ) { if ( N < memo . size ( ) ) return memo . get ( N ) ; for ( int i = memo . size ( ) ; i <= N ; i ++ ) { memo . add ( memo . get ( i - 1 ) + memo . get ( i - 2 ) ) ; } return memo . get ( N ) ; } }
class Solution ( object ) : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . memo = [ ] NEW_LINE self . memo . append ( 0 ) NEW_LINE self . memo . append ( 1 ) NEW_LINE DEDENT def fib ( self , N ) : NEW_LINE INDENT if N < len ( self . memo ) : NEW_LINE INDENT return self . memo [ N ] NEW_LINE DEDENT for i in range ( len ( self . memo ) , N + 1 ) : NEW_LINE INDENT self . memo . append ( self . memo [ i - 1 ] + self . memo [ i - 2 ] ) NEW_LINE DEDENT return self . memo [ N ] NEW_LINE DEDENT DEDENT
T40353
class Solution { public int [ ] [ ] transpose ( int [ ] [ ] A ) { int R = A . length , C = A [ 0 ] . length ; int [ ] [ ] ans = new int [ C ] [ R ] ; for ( int r = 0 ; r < R ; ++ r ) for ( int c = 0 ; c < C ; ++ c ) { ans [ c ] [ r ] = A [ r ] [ c ] ; } return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def transpose ( self , A ) : NEW_LINE INDENT R , C = len ( A ) , len ( A [ 0 ] ) NEW_LINE ans = [ [ None ] * R for _ in xrange ( C ) ] NEW_LINE for r , row in enumerate ( A ) : NEW_LINE INDENT for c , val in enumerate ( row ) : NEW_LINE INDENT ans [ c ] [ r ] = val NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT DEDENT
T40354
class Solution { public int totalFruit ( int [ ] tree ) { int ans = 0 , i = 0 ; Counter count = new Counter ( ) ; for ( int j = 0 ; j < tree . length ; ++ j ) { count . add ( tree [ j ] , 1 ) ; while ( count . size ( ) >= 3 ) { count . add ( tree [ i ] , - 1 ) ; if ( count . get ( tree [ i ] ) == 0 ) count . remove ( tree [ i ] ) ; i ++ ; } ans = Math . max ( ans , j - i + 1 ) ; } return ans ; } } class Counter extends HashMap < Integer , Integer > { public int get ( int k ) { return containsKey ( k ) ? super . get ( k ) : 0 ; } public void add ( int k , int v ) { put ( k , get ( k ) + v ) ; } }
class Solution ( object ) : NEW_LINE INDENT def totalFruit ( self , tree ) : NEW_LINE INDENT ans = i = 0 NEW_LINE count = collections . Counter ( ) NEW_LINE for j , x in enumerate ( tree ) : NEW_LINE INDENT count [ x ] += 1 NEW_LINE while len ( count ) >= 3 : NEW_LINE INDENT count [ tree [ i ] ] -= 1 NEW_LINE if count [ tree [ i ] ] == 0 : NEW_LINE INDENT del count [ tree [ i ] ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT ans = max ( ans , j - i + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT
T40355
class Solution { public boolean canConstruct ( String ransomNote , String magazine ) { int [ ] table = new int [ 128 ] ; for ( char c : magazine . toCharArray ( ) ) table [ c ] ++ ; for ( char c : ransomNote . toCharArray ( ) ) if ( -- table [ c ] < 0 ) return false ; return true ; } }
class Solution ( object ) : NEW_LINE INDENT def canConstruct ( self , ransomNote , magazine ) : NEW_LINE INDENT letter_map = { } NEW_LINE for letter in magazine : NEW_LINE INDENT letter_map [ letter ] = letter_map . get ( letter , 0 ) + 1 NEW_LINE DEDENT for letter in ransomNote : NEW_LINE INDENT letter_map [ letter ] = letter_map . get ( letter , 0 ) - 1 NEW_LINE if letter_map [ letter ] < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT DEDENT
T40356
class Solution { public ListNode reverseList ( ListNode head ) { ListNode newHead = null ; while ( head != null ) { ListNode next = head . next ; head . next = newHead ; newHead = head ; head = next ; } return newHead ; } }
class Solution ( object ) : NEW_LINE INDENT def reverseList ( self , head ) : NEW_LINE INDENT if head is None or head . next is None : NEW_LINE INDENT return head NEW_LINE DEDENT p = self . reverseList ( head . next ) NEW_LINE head . next . next = head NEW_LINE head . next = None NEW_LINE return p NEW_LINE DEDENT DEDENT
T40357
class Solution { public boolean enough ( int x , int m , int n , int k ) { int count = 0 ; for ( int i = 1 ; i <= m ; i ++ ) { count += Math . min ( x / i , n ) ; } return count >= k ; } public int findKthNumber ( int m , int n , int k ) { int lo = 1 , hi = m * n ; while ( lo < hi ) { int mi = lo + ( hi - lo ) / 2 ; if ( ! enough ( mi , m , n , k ) ) lo = mi + 1 ; else hi = mi ; } return lo ; } }
class Solution : NEW_LINE INDENT def findKthNumber ( self , m : int , n : int , k : int ) -> int : NEW_LINE INDENT def enough ( x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT count += min ( x // i , n ) NEW_LINE DEDENT return count >= k NEW_LINE DEDENT lo , hi = 1 , m * n NEW_LINE while lo < hi : NEW_LINE INDENT mi = ( lo + hi ) // 2 NEW_LINE if not enough ( mi ) : NEW_LINE INDENT lo = mi + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi = mi NEW_LINE DEDENT DEDENT return lo NEW_LINE DEDENT DEDENT
T40358
class Solution { public List < Integer > findAnagrams ( String s , String p ) { List < Integer > list = new ArrayList < > ( ) ; if ( s == null || s . length ( ) == 0 || p == null || p . length ( ) == 0 ) return list ; int [ ] hash = new int [ 256 ] ; for ( char c : p . toCharArray ( ) ) { hash [ c ] ++ ; } int left = 0 , right = 0 , count = p . length ( ) ; while ( right < s . length ( ) ) { if ( hash [ s . charAt ( right ++ ) ] -- >= 1 ) count -- ; if ( count == 0 ) list . add ( left ) ; if ( right - left == p . length ( ) && hash [ s . charAt ( left ++ ) ] ++ >= 0 ) count ++ ; } return list ; } }
class Solution ( object ) : NEW_LINE INDENT def findAnagrams ( self , s , p ) : NEW_LINE INDENT res = [ ] NEW_LINE if s is None or p is None or len ( s ) == 0 or len ( p ) == 0 : NEW_LINE INDENT return res NEW_LINE DEDENT char_map = [ 0 ] * 256 NEW_LINE for c in p : NEW_LINE INDENT char_map [ ord ( c ) ] += 1 NEW_LINE DEDENT left , right , count = 0 , 0 , len ( p ) NEW_LINE while right < len ( s ) : NEW_LINE INDENT if char_map [ ord ( s [ right ] ) ] >= 1 : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT char_map [ ord ( s [ right ] ) ] -= 1 NEW_LINE right += 1 NEW_LINE if count == 0 : NEW_LINE INDENT res . append ( left ) NEW_LINE DEDENT if right - left == len ( p ) : NEW_LINE INDENT if char_map [ ord ( s [ left ] ) ] >= 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT char_map [ ord ( s [ left ] ) ] += 1 NEW_LINE left += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT DEDENT
T40359
public class Solution { public TreeNode mergeTrees ( TreeNode t1 , TreeNode t2 ) { if ( t1 == null ) return t2 ; if ( t2 == null ) return t1 ; t1 . val += t2 . val ; t1 . left = mergeTrees ( t1 . left , t2 . left ) ; t1 . right = mergeTrees ( t1 . right , t2 . right ) ; return t1 ; } }
class Solution ( object ) : NEW_LINE INDENT def mergeTrees ( self , t1 , t2 ) : NEW_LINE INDENT if t1 is None : NEW_LINE INDENT return t2 NEW_LINE DEDENT if t2 is None : NEW_LINE INDENT return t1 NEW_LINE DEDENT t1 . val += t2 . val NEW_LINE t1 . left = self . mergeTrees ( t1 . left , t2 . left ) NEW_LINE t1 . right = self . mergeTrees ( t1 . right , t2 . right ) NEW_LINE return t1 NEW_LINE DEDENT DEDENT
T40360
import java . util . Arrays ; import java . util . Collections ; class Solution { public int minMoves ( int [ ] nums ) { if ( nums . length == 0 ) return 0 ; Arrays . sort ( nums ) ; int min_num = nums [ 0 ] ; int ans = 0 ; for ( int num : nums ) { ans += num - min_num ; } return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def minMoves ( self , nums ) : NEW_LINE INDENT if nums is None or len ( nums ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT min_num = min ( nums ) NEW_LINE return sum ( [ i - min_num for i in nums ] ) NEW_LINE DEDENT DEDENT
T40361
class Solution { public int peakIndexInMountainArray ( int [ ] A ) { int lo = 0 , hi = A . length - 1 ; while ( lo < hi ) { int mid = ( lo + hi ) / 2 ; if ( A [ mid ] < A [ mid + 1 ] ) lo = mid + 1 ; else hi = mid ; } return lo ; } }
class Solution ( object ) : NEW_LINE INDENT def peakIndexInMountainArray ( self , A ) : NEW_LINE INDENT lo , hi = 0 , len ( A ) - 1 NEW_LINE while lo < hi : NEW_LINE INDENT mid = ( lo + hi ) / 2 NEW_LINE if A [ mid ] < A [ mid + 1 ] : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid NEW_LINE DEDENT DEDENT return lo NEW_LINE DEDENT DEDENT
T40362
class Solution { public String toLowerCase ( String str ) { return str . toLowerCase ( ) ; } }
class Solution ( object ) : NEW_LINE INDENT def toLowerCase ( self , str ) : NEW_LINE INDENT res = [ ] NEW_LINE gap = ord ( ' a ' ) - ord ( ' A ' ) NEW_LINE for c in str : NEW_LINE INDENT if ord ( c ) >= ord ( ' A ' ) and ord ( c ) <= ord ( ' Z ' ) : NEW_LINE INDENT res . append ( chr ( ord ( c ) + gap ) ) NEW_LINE DEDENT else : NEW_LINE INDENT res . append ( c ) NEW_LINE DEDENT DEDENT return ' ' . join ( res ) NEW_LINE DEDENT DEDENT
T40363
class Solution { public int maxAreaOfIsland ( int [ ] [ ] grid ) { int [ ] dr = new int [ ] { 1 , - 1 , 0 , 0 } ; int [ ] dc = new int [ ] { 0 , 0 , 1 , - 1 } ; int ans = 0 ; for ( int r0 = 0 ; r0 < grid . length ; r0 ++ ) { for ( int c0 = 0 ; c0 < grid [ 0 ] . length ; c0 ++ ) { if ( grid [ r0 ] [ c0 ] == 1 ) { int shape = 0 ; Stack < int [ ] > stack = new Stack ( ) ; stack . push ( new int [ ] { r0 , c0 } ) ; grid [ r0 ] [ c0 ] = 0 ; while ( ! stack . empty ( ) ) { int [ ] node = stack . pop ( ) ; int r = node [ 0 ] , c = node [ 1 ] ; shape ++ ; for ( int k = 0 ; k < 4 ; k ++ ) { int nr = r + dr [ k ] ; int nc = c + dc [ k ] ; if ( 0 <= nr && nr < grid . length && 0 <= nc && nc < grid [ 0 ] . length && grid [ nr ] [ nc ] == 1 ) { stack . push ( new int [ ] { nr , nc } ) ; grid [ nr ] [ nc ] = 0 ; } } } ans = Math . max ( ans , shape ) ; } } } return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def maxAreaOfIsland ( self , grid ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( grid ) ) : NEW_LINE INDENT for j in range ( len ( grid [ 0 ] ) ) : NEW_LINE INDENT if grid [ i ] [ j ] == 1 : NEW_LINE INDENT grid [ i ] [ j ] = 0 NEW_LINE ans = max ( self . dfs ( grid , i , j ) , ans ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT def dfs ( self , grid , i , j ) : NEW_LINE INDENT stack = [ ( i , j ) ] NEW_LINE area = 0 NEW_LINE while stack : NEW_LINE INDENT r , c = stack . pop ( - 1 ) NEW_LINE area += 1 NEW_LINE for nr , nc in ( ( r - 1 , c ) , ( r + 1 , c ) , ( r , c - 1 ) , ( r , c + 1 ) ) : NEW_LINE INDENT if ( 0 <= nr < len ( grid ) and 0 <= nc < len ( grid [ 0 ] ) and grid [ nr ] [ nc ] ) : NEW_LINE INDENT stack . append ( ( nr , nc ) ) NEW_LINE grid [ nr ] [ nc ] = 0 NEW_LINE DEDENT DEDENT DEDENT return area NEW_LINE DEDENT DEDENT
T40364
class Solution { public boolean validateStackSequences ( int [ ] pushed , int [ ] popped ) { Stack < Integer > inStack = new Stack < > ( ) ; int posPush = 0 , posPop = 0 ; while ( posPush != pushed . length ) { int curr = pushed [ posPush ] ; while ( ! inStack . empty ( ) && popped . length > 0 && inStack . peek ( ) == popped [ posPop ] ) { inStack . pop ( ) ; posPop ++ ; } if ( popped . length == 0 ) break ; if ( curr == popped [ posPop ] ) posPop ++ ; else inStack . push ( curr ) ; posPush ++ ; } while ( ! inStack . empty ( ) && popped . length > 0 && inStack . peek ( ) == popped [ posPop ] ) { inStack . pop ( ) ; posPop ++ ; } if ( inStack . empty ( ) ) return true ; return false ; } }
class Solution ( object ) : NEW_LINE INDENT def validateStackSequences ( self , pushed , popped ) : NEW_LINE INDENT in_stack = [ ] NEW_LINE pos = 0 NEW_LINE while pos != len ( pushed ) : NEW_LINE INDENT curr = pushed [ pos ] NEW_LINE while len ( in_stack ) > 0 and len ( popped ) > 0 and in_stack [ - 1 ] == popped [ 0 ] : NEW_LINE INDENT in_stack . pop ( - 1 ) NEW_LINE popped . pop ( 0 ) NEW_LINE DEDENT if len ( popped ) == 0 : NEW_LINE INDENT break NEW_LINE DEDENT if curr == popped [ 0 ] : NEW_LINE INDENT popped . pop ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT in_stack . append ( curr ) NEW_LINE DEDENT pos += 1 NEW_LINE DEDENT while len ( in_stack ) > 0 and len ( popped ) > 0 and in_stack [ - 1 ] == popped [ 0 ] : NEW_LINE INDENT in_stack . pop ( - 1 ) NEW_LINE popped . pop ( 0 ) NEW_LINE DEDENT if len ( in_stack ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = Solution ( ) NEW_LINE print s . validateStackSequences ( [ 1 , 0 , 3 , 2 ] , [ 0 , 1 , 2 , 3 ] ) NEW_LINE DEDENT
T40365
class Solution { public int minMeetingRooms ( Interval [ ] intervals ) { int ans = 0 , curr = 0 ; List < TimePoint > timeline = new ArrayList < > ( ) ; for ( Interval interval : intervals ) { timeline . add ( new TimePoint ( interval . start , 1 ) ) ; timeline . add ( new TimePoint ( interval . end , - 1 ) ) ; } timeline . sort ( new Comparator < TimePoint > ( ) { public int compare ( TimePoint a , TimePoint b ) { if ( a . time != b . time ) return a . time - b . time ; else return a . room - b . room ; } } ) ; for ( TimePoint t : timeline ) { curr += t . room ; if ( curr >= ans ) ans = curr ; } return ans ; } private class TimePoint { int time ; int room ; TimePoint ( int time , int room ) { this . time = time ; this . room = room ; } } }
class Solution ( object ) : NEW_LINE INDENT def minMeetingRooms ( self , intervals ) : NEW_LINE INDENT timeline = [ ] NEW_LINE for interval in intervals : NEW_LINE INDENT timeline . append ( ( interval . start , 1 ) ) NEW_LINE timeline . append ( ( interval . end , - 1 ) ) NEW_LINE DEDENT timeline . sort ( ) NEW_LINE ans = curr = 0 NEW_LINE for _ , v in timeline : NEW_LINE INDENT curr += v NEW_LINE ans = max ( ans , curr ) NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT
T40366
class Solution { public String longestWord ( String [ ] words ) { Trie trie = new Trie ( ) ; int index = 0 ; for ( String word : words ) { trie . insert ( word , ++ index ) ; } trie . words = words ; return trie . dfs ( ) ; } } class Node { char c ; HashMap < Character , Node > children = new HashMap ( ) ; int end ; public Node ( char c ) { this . c = c ; } } class Trie { Node root ; String [ ] words ; public Trie ( ) { root = new Node ( '0' ) ; } public void insert ( String word , int index ) { Node cur = root ; for ( char c : word . toCharArray ( ) ) { cur . children . putIfAbsent ( c , new Node ( c ) ) ; cur = cur . children . get ( c ) ; } cur . end = index ; } public String dfs ( ) { String ans = " " ; Stack < Node > stack = new Stack ( ) ; stack . push ( root ) ; while ( ! stack . empty ( ) ) { Node node = stack . pop ( ) ; if ( node . end > 0 || node == root ) { if ( node != root ) { String word = words [ node . end - 1 ] ; if ( word . length ( ) > ans . length ( ) || word . length ( ) == ans . length ( ) && word . compareTo ( ans ) < 0 ) { ans = word ; } } for ( Node nei : node . children . values ( ) ) { stack . push ( nei ) ; } } } return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def longestWord ( self , words ) : NEW_LINE INDENT Trie = lambda : collections . defaultdict ( Trie ) NEW_LINE trie = Trie ( ) NEW_LINE END = True NEW_LINE for i , word in enumerate ( words ) : NEW_LINE INDENT reduce ( dict . __getitem__ , word , trie ) [ END ] = i NEW_LINE DEDENT stack = trie . values ( ) NEW_LINE ans = " " NEW_LINE while stack : NEW_LINE INDENT cur = stack . pop ( ) NEW_LINE if END in cur : NEW_LINE INDENT word = words [ cur [ END ] ] NEW_LINE if len ( word ) > len ( ans ) or len ( word ) == len ( ans ) and word < ans : NEW_LINE INDENT ans = word NEW_LINE DEDENT stack . extend ( [ cur [ letter ] for letter in cur if letter != END ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT DEDENT
T40367
import java . util . ArrayList ; import java . util . List ; class MinStack { private Stack < Integer > stack ; private Stack < Integer > minStack ; public MinStack ( ) { stack = new Stack < > ( ) ; minStack = new Stack < > ( ) ; } public void push ( int x ) { stack . push ( x ) ; if ( minStack . size ( ) == 0 || x <= minStack . peek ( ) ) minStack . push ( x ) ; else minStack . push ( minStack . peek ( ) ) ; } public void pop ( ) { stack . pop ( ) ; minStack . pop ( ) ; } public int top ( ) { return stack . peek ( ) ; } public int getMin ( ) { return minStack . peek ( ) ; } }
class MinStack ( object ) : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . stack = [ ] NEW_LINE self . min_stack = [ ] NEW_LINE DEDENT def push ( self , x ) : NEW_LINE INDENT self . stack . append ( x ) NEW_LINE if len ( self . min_stack ) == 0 : NEW_LINE INDENT self . min_stack . append ( x ) NEW_LINE return NEW_LINE DEDENT if x <= self . min_stack [ - 1 ] : NEW_LINE INDENT self . min_stack . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT self . min_stack . append ( self . min_stack [ - 1 ] ) NEW_LINE DEDENT DEDENT def pop ( self ) : NEW_LINE INDENT if len ( self . stack ) > 0 : NEW_LINE INDENT self . min_stack . pop ( ) NEW_LINE self . stack . pop ( ) NEW_LINE DEDENT DEDENT def top ( self ) : NEW_LINE INDENT if len ( self . stack ) > 0 : NEW_LINE INDENT return self . stack [ - 1 ] NEW_LINE DEDENT return None NEW_LINE DEDENT def getMin ( self ) : NEW_LINE INDENT if len ( self . min_stack ) > 0 : NEW_LINE INDENT return self . min_stack [ - 1 ] NEW_LINE DEDENT return None NEW_LINE DEDENT DEDENT
T40368
class Solution { public int minIncrementForUnique ( int [ ] A ) { if ( A . length == 0 ) return 0 ; HashSet < Integer > numSet = new HashSet < > ( ) ; List < Integer > duplicated = new ArrayList < > ( ) ; int res = 0 ; Arrays . sort ( A ) ; int left = A [ 0 ] ; int right = A [ A . length - 1 ] ; int holes = right - left + 1 ; for ( int v : A ) { if ( numSet . contains ( v ) ) duplicated . add ( v ) ; else numSet . add ( v ) ; } holes -= numSet . size ( ) ; for ( int i = left + 1 ; i < right ; i ++ ) { if ( holes == 0 || duplicated . size ( ) == 0 ) break ; if ( ! numSet . contains ( i ) && i > duplicated . get ( 0 ) ) { res += i - duplicated . get ( 0 ) ; holes -- ; duplicated . remove ( 0 ) ; } } if ( duplicated . size ( ) == 0 ) return res ; while ( duplicated . size ( ) != 0 ) { right += 1 ; res += right - duplicated . get ( 0 ) ; duplicated . remove ( 0 ) ; } return res ; } }
class Solution ( object ) : NEW_LINE INDENT def minIncrementForUnique ( self , A ) : NEW_LINE INDENT if A is None or len ( A ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE num_set = set ( ) NEW_LINE duplicate = [ ] NEW_LINE A . sort ( ) NEW_LINE left , right = A [ 0 ] , A [ - 1 ] NEW_LINE holes = right - left + 1 NEW_LINE for v in A : NEW_LINE INDENT if v in num_set : NEW_LINE INDENT duplicate . append ( v ) NEW_LINE DEDENT else : NEW_LINE INDENT num_set . add ( v ) NEW_LINE DEDENT DEDENT holes = holes - len ( num_set ) NEW_LINE for hole in range ( left + 1 , right ) : NEW_LINE INDENT if holes == 0 or len ( duplicate ) == 0 : NEW_LINE INDENT break NEW_LINE DEDENT if hole not in num_set and hole > duplicate [ 0 ] : NEW_LINE INDENT res += hole - duplicate . pop ( 0 ) NEW_LINE holes -= 1 NEW_LINE DEDENT DEDENT while len ( duplicate ) != 0 : NEW_LINE INDENT right += 1 NEW_LINE res += right - duplicate . pop ( 0 ) NEW_LINE DEDENT return res NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = Solution ( ) NEW_LINE DEDENT
T40369
class Solution { public boolean isPalindrome ( int x ) { if ( x < 0 ) return false ; int temp = x ; int len = 0 ; while ( temp != 0 ) { temp /= 10 ; len ++ ; } temp = x ; int left , right ; for ( int i = 0 ; i < len / 2 ; i ++ ) { right = temp % 10 ; left = temp / ( int ) Math . pow ( 10 , len - 2 * i - 1 ) ; left = left % 10 ; if ( left != right ) return false ; temp /= 10 ; } return true ; } public boolean isPalindrome ( int x ) { if ( x < 0 ) return false ; int div = 1 ; while ( x / div >= 10 ) { div *= 10 ; } while ( x != 0 ) { int l = x / div ; int r = x % 10 ; if ( l != r ) return false ; x = ( x % div ) / 10 ; div /= 100 ; } return true ; } } class Solution { public boolean isPalindrome ( int x ) { int r , s = 0 , number = x ; if ( number < 0 ) { return false ; } while ( number != 0 ) { r = number % 10 ; s = s * 10 + r ; number /= 10 ; } if ( s == x ) { return true ; } else { return false ; } } }
class Solution ( object ) : NEW_LINE INDENT def isPalindrome ( self , x ) : NEW_LINE INDENT if x < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT ls = len ( str ( x ) ) NEW_LINE tmp = x NEW_LINE for i in range ( int ( ls / 2 ) ) : NEW_LINE INDENT right = int ( tmp % 10 ) NEW_LINE left = tmp / ( 10 ** ( ls - 2 * i - 1 ) ) NEW_LINE left = int ( left % 10 ) NEW_LINE if left != right : NEW_LINE INDENT return False NEW_LINE DEDENT tmp = tmp // 10 NEW_LINE DEDENT return True NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = Solution ( ) NEW_LINE print s . isPalindrome ( 1001 ) NEW_LINE DEDENT
T40370
class Solution { public List < String > readBinaryWatch ( int num ) { List < String > times = new ArrayList < > ( ) ; for ( int h = 0 ; h < 12 ; h ++ ) for ( int m = 0 ; m < 60 ; m ++ ) if ( Integer . bitCount ( h * 64 + m ) == num ) times . add ( String . format ( " % d : %02d " , h , m ) ) ; return times ; } }
class Solution ( object ) : NEW_LINE INDENT def readBinaryWatch ( self , num ) : NEW_LINE INDENT return [ ' % d : %02d ' % ( h , m ) for h in range ( 12 ) for m in range ( 60 ) if ( bin ( h ) + bin ( m ) ) . count ( '1' ) == num ] NEW_LINE DEDENT DEDENT
T40371
class Solution { public int fixedPoint ( int [ ] A ) { int l = 0 ; int h = A . length ; while ( l <= h ) { int mid = ( l + h ) / 2 ; if ( A [ mid ] > mid ) h = mid - 1 ; else if ( A [ mid ] < mid ) l = mid + 1 ; else return mid ; } return - 1 ; } }
class Solution ( object ) : NEW_LINE INDENT def fixedPoint ( self , A ) : NEW_LINE INDENT l , h = 0 , len ( A ) - 1 NEW_LINE while l <= h : NEW_LINE INDENT mid = ( l + h ) // 2 NEW_LINE if A [ mid ] < mid : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT elif A [ mid ] > mid : NEW_LINE INDENT h = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return mid NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT DEDENT
T40372
import java . util . ArrayList ; import java . util . List ; class Solution { public List < String > fizzBuzz ( int n ) { List < String > res = new ArrayList < > ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { String tmp = " " ; if ( i % 3 == 0 ) tmp += " Fizz " ; if ( i % 5 == 0 ) tmp += " Buzz " ; if ( tmp . length ( ) == 0 ) tmp += String . valueOf ( i ) ; res . add ( tmp ) ; } return res ; } }
class Solution ( object ) : NEW_LINE INDENT def fizzBuzz ( self , n ) : NEW_LINE INDENT return [ str ( i ) * ( i % 3 != 0 and i % 5 != 0 ) + " Fizz " * ( i % 3 == 0 ) + " Buzz " * ( i % 5 == 0 ) for i in range ( 1 , n + 1 ) ] NEW_LINE DEDENT DEDENT
T40373
public class Solution { public String longestPalindrome ( String s ) { int start = 0 , end = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int len1 = expandAroundCenter ( s , i , i ) ; int len2 = expandAroundCenter ( s , i , i + 1 ) ; int len = Math . max ( len1 , len2 ) ; if ( len > end - start ) { start = i - ( len - 1 ) / 2 ; end = i + len / 2 ; } } return s . substring ( start , end + 1 ) ; } private int expandAroundCenter ( String s , int left , int right ) { int L = left , R = right ; while ( L >= 0 && R < s . length ( ) && s . charAt ( L ) == s . charAt ( R ) ) { L -- ; R ++ ; } return R - L - 1 ; } }
class Solution ( object ) : NEW_LINE INDENT def longestPalindrome ( self , s ) : NEW_LINE INDENT ls = len ( s ) NEW_LINE if ls <= 1 or len ( set ( s ) ) == 1 : NEW_LINE INDENT return s NEW_LINE DEDENT temp_s = ' # ' . join ( ' { } ' . format ( s ) ) NEW_LINE tls = len ( temp_s ) NEW_LINE seed = range ( 1 , tls - 1 ) NEW_LINE len_table = [ 0 ] * tls NEW_LINE for step in range ( 1 , tls / 2 + 1 ) : NEW_LINE INDENT final = [ ] NEW_LINE for pos in seed : NEW_LINE INDENT if pos - step < 0 or pos + step >= tls : NEW_LINE INDENT continue NEW_LINE DEDENT if temp_s [ pos - step ] != temp_s [ pos + step ] : NEW_LINE INDENT continue NEW_LINE DEDENT final . append ( pos ) NEW_LINE if temp_s [ pos - step ] == ' # ' : NEW_LINE INDENT continue NEW_LINE DEDENT len_table [ pos ] = step NEW_LINE DEDENT seed = final NEW_LINE DEDENT max_pos , max_step = 0 , 0 NEW_LINE for i , s in enumerate ( len_table ) : NEW_LINE INDENT if s >= max_step : NEW_LINE INDENT max_step = s NEW_LINE max_pos = i NEW_LINE DEDENT DEDENT return temp_s [ max_pos - max_step : max_pos + max_step + 1 ] . translate ( None , ' # ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = Solution ( ) NEW_LINE print s . longestPalindrome ( " abcbe " ) NEW_LINE DEDENT
T40374
class Solution { public boolean isOneBitCharacter ( int [ ] bits ) { int pos = 0 ; while ( pos < bits . length - 1 ) { pos += bits [ pos ] + 1 ; } return pos == bits . length - 1 ; } }
class Solution : NEW_LINE INDENT def isOneBitCharacter ( self , bits : List [ int ] ) -> bool : NEW_LINE INDENT pos = 0 NEW_LINE while pos < len ( bits ) - 1 : NEW_LINE INDENT pos += bits [ pos ] + 1 NEW_LINE DEDENT return pos == len ( bits ) - 1 NEW_LINE DEDENT DEDENT
T40375
public class Solution { private static final int maxDiv10 = Integer . MAX_VALUE / 10 ; public int myAtoi ( String str ) { int i = 0 , n = str . length ( ) ; while ( i < n && Character . isWhitespace ( str . charAt ( i ) ) ) i ++ ; int sign = 1 ; if ( i < n && str . charAt ( i ) == ' + ' ) i ++ ; else if ( i < n && str . charAt ( i ) == ' - ' ) { sign = - 1 ; i ++ ; } int num = 0 ; while ( i < n && Character . isDigit ( str . charAt ( i ) ) ) { int digit = Character . getNumericValue ( str . charAt ( i ) ) ; if ( num > maxDiv10 || num == maxDiv10 && digit >= 8 ) return sign == 1 ? Integer . MAX_VALUE : Integer . MIN_VALUE ; num = num * 10 + digit ; i ++ ; } return sign * num ; } }
class Solution ( object ) : NEW_LINE INDENT def myAtoi ( self , str ) : NEW_LINE INDENT sign = 1 NEW_LINE max_int , min_int = 2147483647 , - 2147483648 NEW_LINE result , pos = 0 , 0 NEW_LINE ls = len ( str ) NEW_LINE while pos < ls and str [ pos ] == ' ▁ ' : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT if pos < ls and str [ pos ] == ' - ' : NEW_LINE INDENT sign = - 1 NEW_LINE pos += 1 NEW_LINE DEDENT elif pos < ls and str [ pos ] == ' + ' : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT while pos < ls and ord ( str [ pos ] ) >= ord ( '0' ) and ord ( str [ pos ] ) <= ord ( '9' ) : NEW_LINE INDENT num = ord ( str [ pos ] ) - ord ( '0' ) NEW_LINE if result > max_int / 10 or ( result == max_int / 10 and num >= 8 ) : NEW_LINE INDENT if sign == - 1 : NEW_LINE INDENT return min_int NEW_LINE DEDENT return max_int NEW_LINE DEDENT result = result * 10 + num NEW_LINE pos += 1 NEW_LINE DEDENT return sign * result NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = Solution ( ) NEW_LINE print s . myAtoi ( " + - 2" ) NEW_LINE DEDENT
T40376
class Solution { public String mostCommonWord ( String paragraph , String [ ] banned ) { paragraph += " . " ; Set < String > banset = new HashSet ( ) ; for ( String word : banned ) banset . add ( word ) ; Map < String , Integer > count = new HashMap ( ) ; String ans = " " ; int ansfreq = 0 ; StringBuilder word = new StringBuilder ( ) ; for ( char c : paragraph . toCharArray ( ) ) { if ( Character . isLetter ( c ) ) { word . append ( Character . toLowerCase ( c ) ) ; } else if ( word . length ( ) > 0 ) { String finalword = word . toString ( ) ; if ( ! banset . contains ( finalword ) ) { count . put ( finalword , count . getOrDefault ( finalword , 0 ) + 1 ) ; if ( count . get ( finalword ) > ansfreq ) { ans = finalword ; ansfreq = count . get ( finalword ) ; } } word = new StringBuilder ( ) ; } } return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def mostCommonWord ( self , paragraph , banned ) : NEW_LINE INDENT banned = set ( banned ) NEW_LINE count = collections . Counter ( word for word in re . split ( ' [ ▁ ! ? \ ' , ; . ] ' , paragraph . lower ( ) ) if word ) NEW_LINE return max ( ( item for item in count . items ( ) if item [ 0 ] not in banned ) , key = operator . itemgetter ( 1 ) ) [ 0 ] NEW_LINE DEDENT DEDENT
T40377
public class Solution { HashSet < String > trees = new HashSet < > ( ) ; public boolean isSubtree ( TreeNode s , TreeNode t ) { String tree1 = preorder ( s , true ) ; String tree2 = preorder ( t , true ) ; return tree1 . indexOf ( tree2 ) >= 0 ; } public String preorder ( TreeNode t , boolean left ) { if ( t == null ) { if ( left ) return " lnull " ; else return " rnull " ; } return " # " + t . val + " ▁ " + preorder ( t . left , true ) + " ▁ " + preorder ( t . right , false ) ; } }
class Solution ( object ) : NEW_LINE INDENT def isSubtree ( self , s , t ) : NEW_LINE INDENT s_res = self . preorder ( s , True ) NEW_LINE t_res = self . preorder ( t , True ) NEW_LINE return t_res in s_res NEW_LINE DEDENT def preorder ( self , root , isLeft ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT if isLeft : NEW_LINE INDENT return " lnull " NEW_LINE DEDENT else : NEW_LINE INDENT return " rnull " NEW_LINE DEDENT DEDENT return " # " + str ( root . val ) + " ▁ " + self . preorder ( root . left , True ) + " ▁ " + self . preorder ( root . right , False ) NEW_LINE DEDENT DEDENT
T40378
class Solution { public List < Integer > topKFrequent ( int [ ] nums , int k ) { HashMap < Integer , Integer > count = new HashMap ( ) ; for ( int n : nums ) { count . put ( n , count . getOrDefault ( n , 0 ) + 1 ) ; } PriorityQueue < Integer > heap = new PriorityQueue < Integer > ( ( n1 , n2 ) -> count . get ( n1 ) - count . get ( n2 ) ) ; for ( int n : count . keySet ( ) ) { heap . add ( n ) ; if ( heap . size ( ) > k ) heap . poll ( ) ; } List < Integer > top_k = new LinkedList ( ) ; while ( ! heap . isEmpty ( ) ) top_k . add ( heap . poll ( ) ) ; Collections . reverse ( top_k ) ; return top_k ; } }
class Solution ( object ) : NEW_LINE INDENT def topKFrequent ( self , nums , k ) : NEW_LINE INDENT counter = collections . Counter ( nums ) NEW_LINE return [ k for k , v in counter . most_common ( k ) ] NEW_LINE DEDENT DEDENT
T40379
class Solution { public int poorPigs ( int buckets , int minutesToDie , int minutesToTest ) { int n = minutesToTest / minutesToDie + 1 ; int pigs = 0 ; while ( Math . pow ( n , pigs ) < buckets ) pigs ++ ; return pigs ; } }
class Solution ( object ) : NEW_LINE INDENT def poorPigs ( self , buckets , minutesToDie , minutesToTest ) : NEW_LINE INDENT pigs = 0 NEW_LINE while ( minutesToTest / minutesToDie + 1 ) ** pigs < buckets : NEW_LINE INDENT pigs += 1 NEW_LINE DEDENT return pigs NEW_LINE DEDENT DEDENT
T40380
import java . util . List ; class Solution { public String [ ] reorderLogFiles ( String [ ] logs ) { Arrays . sort ( logs , ( log1 , log2 ) -> { String [ ] split1 = log1 . split ( " ▁ " , 2 ) ; String [ ] split2 = log2 . split ( " ▁ " , 2 ) ; boolean isDigit1 = Character . isDigit ( split1 [ 1 ] . charAt ( 0 ) ) ; boolean isDigit2 = Character . isDigit ( split2 [ 1 ] . charAt ( 0 ) ) ; if ( ! isDigit1 && ! isDigit2 ) { int cmp = split1 [ 1 ] . compareTo ( split2 [ 1 ] ) ; if ( cmp != 0 ) return cmp ; return split1 [ 0 ] . compareTo ( split2 [ 0 ] ) ; } return isDigit1 ? ( isDigit2 ? 0 : 1 ) : - 1 ; } ) ; return logs ; } }
class Solution ( object ) : NEW_LINE INDENT def reorderLogFiles ( self , logs ) : NEW_LINE INDENT letter_logs = [ ] NEW_LINE digit_logs = [ ] NEW_LINE for log in logs : NEW_LINE INDENT if log . split ( ' ▁ ' ) [ 1 ] . isnumeric ( ) : NEW_LINE INDENT digit_logs . append ( log ) NEW_LINE DEDENT else : NEW_LINE INDENT letter_logs . append ( log ) NEW_LINE DEDENT DEDENT return sorted ( letter_logs , key = lambda x : x . split ( ' ▁ ' ) [ 1 : ] + x . split ( ' ▁ ' ) [ 0 ] ) + digit_logs NEW_LINE DEDENT DEDENT
T40381
import java . util . Stack ; import javax . swing . tree . TreeNode ; class Solution { public int sumOfLeftLeaves ( TreeNode root ) { int res = 0 ; Stack < TreeNode > stack = new Stack < > ( ) ; stack . push ( root ) ; while ( ! stack . isEmpty ( ) ) { TreeNode node = stack . pop ( ) ; if ( node != null ) { if ( node . left != null && node . left . left == null && node . left . right == null ) res += node . left . val ; stack . push ( node . right ) ; stack . push ( node . left ) ; } } return res ; } }
class Solution ( object ) : NEW_LINE INDENT def sumOfLeftLeaves ( self , root ) : NEW_LINE INDENT stack = [ root ] NEW_LINE res = 0 NEW_LINE while len ( stack ) > 0 : NEW_LINE INDENT curr = stack . pop ( 0 ) NEW_LINE if curr is not None : NEW_LINE INDENT if curr . left is not None : NEW_LINE INDENT if curr . left . left is None and curr . left . right is None : NEW_LINE INDENT res += curr . left . val NEW_LINE DEDENT DEDENT stack . insert ( 0 , curr . right ) NEW_LINE stack . insert ( 0 , curr . left ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT DEDENT
T40382
class Solution { public int countPrimes ( int n ) { boolean [ ] isPrime = new boolean [ n ] ; int count = 0 ; Arrays . fill ( isPrime , true ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( i * i >= n ) break ; if ( ! isPrime [ i ] ) continue ; for ( int j = i * i ; j < n ; j += i ) isPrime [ j ] = false ; } for ( int i = 2 ; i < n ; i ++ ) if ( isPrime [ i ] ) count ++ ; return count ; } }
class Solution ( object ) : NEW_LINE INDENT def countPrimes ( self , n ) : NEW_LINE INDENT isPrime = [ True ] * n NEW_LINE for i in xrange ( 2 , n ) : NEW_LINE INDENT if i * i >= n : NEW_LINE INDENT break NEW_LINE DEDENT if not isPrime [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT for j in xrange ( i * i , n , i ) : NEW_LINE INDENT isPrime [ j ] = False NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in xrange ( 2 , n ) : NEW_LINE INDENT if isPrime [ i ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT DEDENT
T40383
class Solution { public boolean backspaceCompare ( String S , String T ) { return trans ( S ) . equals ( trans ( T ) ) ; } private String trans ( String str ) { StringBuilder sb = new StringBuilder ( ) ; for ( char c : str . toCharArray ( ) ) { if ( c != ' # ' ) { sb . append ( c ) ; } else if ( sb . length ( ) > 0 ) { sb . deleteCharAt ( sb . length ( ) - 1 ) ; } } return sb . toString ( ) ; } }
class Solution ( object ) : NEW_LINE INDENT def backspaceCompare ( self , S , T ) : NEW_LINE INDENT if S == T : NEW_LINE INDENT return True NEW_LINE DEDENT s_stack = [ ] NEW_LINE t_stack = [ ] NEW_LINE for c in S : NEW_LINE INDENT if c != ' # ' : NEW_LINE INDENT s_stack . append ( c ) NEW_LINE DEDENT elif len ( s_stack ) != 0 : NEW_LINE INDENT s_stack . pop ( - 1 ) NEW_LINE DEDENT DEDENT for c in T : NEW_LINE INDENT if c != ' # ' : NEW_LINE INDENT t_stack . append ( c ) NEW_LINE DEDENT elif len ( t_stack ) != 0 : NEW_LINE INDENT t_stack . pop ( - 1 ) NEW_LINE DEDENT DEDENT return ' ' . join ( s_stack ) == ' ' . join ( t_stack ) NEW_LINE DEDENT DEDENT
T40384
class Solution { Map < Integer , Integer > dist ; public int networkDelayTime ( int [ ] [ ] times , int N , int K ) { Map < Integer , List < int [ ] > > graph = new HashMap ( ) ; for ( int [ ] edge : times ) { if ( ! graph . containsKey ( edge [ 0 ] ) ) graph . put ( edge [ 0 ] , new ArrayList < int [ ] > ( ) ) ; graph . get ( edge [ 0 ] ) . add ( new int [ ] { edge [ 1 ] , edge [ 2 ] } ) ; } dist = new HashMap ( ) ; for ( int node = 1 ; node <= N ; ++ node ) dist . put ( node , Integer . MAX_VALUE ) ; dist . put ( K , 0 ) ; boolean [ ] seen = new boolean [ N + 1 ] ; while ( true ) { int candNode = - 1 ; int candDist = Integer . MAX_VALUE ; for ( int i = 1 ; i <= N ; ++ i ) { if ( ! seen [ i ] && dist . get ( i ) < candDist ) { candDist = dist . get ( i ) ; candNode = i ; } } if ( candNode < 0 ) break ; seen [ candNode ] = true ; if ( graph . containsKey ( candNode ) ) for ( int [ ] info : graph . get ( candNode ) ) dist . put ( info [ 0 ] , Math . min ( dist . get ( info [ 0 ] ) , dist . get ( candNode ) + info [ 1 ] ) ) ; } int ans = 0 ; for ( int cand : dist . values ( ) ) { if ( cand == Integer . MAX_VALUE ) return - 1 ; ans = Math . max ( ans , cand ) ; } return ans ; } }
class Solution ( object ) : NEW_LINE INDENT def networkDelayTime ( self , times , N , K ) : NEW_LINE INDENT graph = collections . defaultdict ( list ) NEW_LINE for u , v , w in times : NEW_LINE INDENT graph [ u ] . append ( ( v , w ) ) NEW_LINE DEDENT dist = { node : float ( ' inf ' ) for node in xrange ( 1 , N + 1 ) } NEW_LINE seen = [ False ] * ( N + 1 ) NEW_LINE dist [ K ] = 0 NEW_LINE while True : NEW_LINE INDENT cand_node = - 1 NEW_LINE cand_dist = float ( ' inf ' ) NEW_LINE for i in xrange ( 1 , N + 1 ) : NEW_LINE INDENT if not seen [ i ] and dist [ i ] < cand_dist : NEW_LINE INDENT cand_dist = dist [ i ] NEW_LINE cand_node = i NEW_LINE DEDENT DEDENT if cand_node < 0 : break NEW_LINE seen [ cand_node ] = True NEW_LINE for nei , d in graph [ cand_node ] : NEW_LINE INDENT dist [ nei ] = min ( dist [ nei ] , dist [ cand_node ] + d ) NEW_LINE DEDENT DEDENT ans = max ( dist . values ( ) ) NEW_LINE return ans if ans < float ( ' inf ' ) else - 1 NEW_LINE DEDENT DEDENT
T40385
class Solution { private final String [ ] LESS_THAN_20 = { " " , " One " , " Two " , " Three " , " Four " , " Five " , " Six " , " Seven " , " Eight " , " Nine " , " Ten " , " Eleven " , " Twelve " , " Thirteen " , " Fourteen " , " Fifteen " , " Sixteen " , " Seventeen " , " Eighteen " , " Nineteen " } ; private final String [ ] TENS = { " " , " Ten " , " Twenty " , " Thirty " , " Forty " , " Fifty " , " Sixty " , " Seventy " , " Eighty " , " Ninety " } ; private final String [ ] THOUSANDS = { " " , " Thousand " , " Million " , " Billion " } ; public String numberToWords ( int num ) { if ( num == 0 ) return " Zero " ; int i = 0 ; String words = " " ; while ( num > 0 ) { if ( num % 1000 != 0 ) words = helper ( num % 1000 ) + THOUSANDS [ i ] + " ▁ " + words ; num /= 1000 ; i ++ ; } return words . trim ( ) ; } private String helper ( int num ) { if ( num == 0 ) return " " ; else if ( num < 20 ) return LESS_THAN_20 [ num ] + " ▁ " ; else if ( num < 100 ) return TENS [ num / 10 ] + " ▁ " + helper ( num % 10 ) ; else return LESS_THAN_20 [ num / 100 ] + " ▁ Hundred ▁ " + helper ( num % 100 ) ; } }
class Solution ( object ) : NEW_LINE INDENT def numberToWords ( self , num ) : NEW_LINE INDENT to19 = ' One ▁ Two ▁ Three ▁ Four ▁ Five ▁ Six ▁ Seven ▁ Eight ▁ Nine ▁ Ten ▁ Eleven ▁ Twelve ▁ ' ' Thirteen ▁ Fourteen ▁ Fifteen ▁ Sixteen ▁ Seventeen ▁ Eighteen ▁ Nineteen ' . split ( ) NEW_LINE tens = ' Twenty ▁ Thirty ▁ Forty ▁ Fifty ▁ Sixty ▁ Seventy ▁ Eighty ▁ Ninety ' . split ( ) NEW_LINE def words ( n ) : NEW_LINE INDENT if n < 20 : NEW_LINE INDENT return to19 [ n - 1 : n ] NEW_LINE DEDENT if n < 100 : NEW_LINE INDENT return [ tens [ n / 10 - 2 ] ] + words ( n % 10 ) NEW_LINE DEDENT if n < 1000 : NEW_LINE INDENT return [ to19 [ n / 100 - 1 ] ] + [ ' Hundred ' ] + words ( n % 100 ) NEW_LINE DEDENT for p , w in enumerate ( ( ' Thousand ' , ' Million ' , ' Billion ' ) , 1 ) : NEW_LINE INDENT if n < 1000 ** ( p + 1 ) : NEW_LINE INDENT return words ( n / 1000 ** p ) + [ w ] + words ( n % 1000 ** p ) NEW_LINE DEDENT DEDENT DEDENT return ' ▁ ' . join ( words ( num ) ) or ' Zero ' NEW_LINE DEDENT DEDENT
T40386
class Solution { public ListNode middleNode ( ListNode head ) { ListNode fast , slow ; fast = slow = head ; while ( fast != null && fast . next != null ) { slow = slow . next ; fast = fast . next . next ; } return slow ; } }
class Solution ( object ) : NEW_LINE INDENT def middleNode ( self , head ) : NEW_LINE INDENT fast = slow = head NEW_LINE while fast and fast . next : NEW_LINE INDENT slow = slow . next NEW_LINE fast = fast . next . next NEW_LINE DEDENT return slow NEW_LINE DEDENT DEDENT
T40387
class Solution { public int islandPerimeter ( int [ ] [ ] grid ) { int islands = 0 , neighbours = 0 ; for ( int i = 0 ; i < grid . length ; i ++ ) { for ( int j = 0 ; j < grid [ i ] . length ; j ++ ) { if ( grid [ i ] [ j ] == 1 ) { islands ++ ; if ( i < grid . length - 1 && grid [ i + 1 ] [ j ] == 1 ) neighbours ++ ; if ( j < grid [ i ] . length - 1 && grid [ i ] [ j + 1 ] == 1 ) neighbours ++ ; } } } return islands * 4 - neighbours * 2 ; } }
class Solution ( object ) : NEW_LINE INDENT def islandPerimeter ( self , grid ) : NEW_LINE INDENT row_num = len ( grid ) NEW_LINE if row_num == 0 | | len ( grid [ 0 ] ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT islands , overlaps = 0 , 0 NEW_LINE col_num = len ( grid [ 0 ] ) NEW_LINE for i in range ( row_num ) : NEW_LINE INDENT for j in range ( col_num ) : NEW_LINE INDENT if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT islands += 1 NEW_LINE if ( i < row_num - 1 & & grid [ i + 1 ] [ j ] == 1 ) : NEW_LINE INDENT overlaps += 1 NEW_LINE DEDENT if ( j < col_num - 1 & & grid [ i ] [ j + 1 ] == 1 ) : NEW_LINE INDENT overlaps += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return islands * 4 - overlaps * 2 NEW_LINE DEDENT DEDENT
T40388
public class Solution { public int [ ] twoSum ( int [ ] nums , int target ) { Map < Integer , Integer > map = new HashMap < > ( ) ; for ( int i = 0 ; i < nums . length ; i ++ ) { int x = nums [ i ] ; if ( map . containsKey ( target - x ) ) { return new int [ ] { map . get ( target - x ) , i } ; } map . put ( x , i ) ; } throw new IllegalArgumentException ( " No ▁ two ▁ sum ▁ solution " ) ; } }
class Solution ( object ) : NEW_LINE INDENT def twoSum ( self , nums , target ) : NEW_LINE INDENT nums_index = [ ( v , index ) for index , v in enumerate ( nums ) ] NEW_LINE nums_index . sort ( ) NEW_LINE begin , end = 0 , len ( nums ) - 1 NEW_LINE while begin < end : NEW_LINE INDENT curr = nums_index [ begin ] [ 0 ] + nums_index [ end ] [ 0 ] NEW_LINE if curr == target : NEW_LINE INDENT return [ nums_index [ begin ] [ 1 ] , nums_index [ end ] [ 1 ] ] NEW_LINE DEDENT elif curr < target : NEW_LINE INDENT begin += 1 NEW_LINE DEDENT else : NEW_LINE INDENT end -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = Solution ( ) NEW_LINE print s . twoSum ( [ 3 , 2 , 4 ] , 6 ) NEW_LINE DEDENT
T40389
public class Solution { public int lengthOfLongestSubstring ( String s ) { int [ ] charMap = new int [ 256 ] ; Arrays . fill ( charMap , - 1 ) ; int i = 0 , maxLen = 0 ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { if ( charMap [ s . charAt ( j ) ] >= i ) { i = charMap [ s . charAt ( j ) ] + 1 ; } charMap [ s . charAt ( j ) ] = j ; maxLen = Math . max ( j - i + 1 , maxLen ) ; } return maxLen ; } }
class Solution ( object ) : NEW_LINE INDENT def lengthOfLongestSubstring ( self , s ) : NEW_LINE INDENT charMap = { } NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT charMap [ i ] = - 1 NEW_LINE DEDENT ls = len ( s ) NEW_LINE i = max_len = 0 NEW_LINE for j in range ( ls ) : NEW_LINE INDENT if charMap [ ord ( s [ j ] ) ] >= i : NEW_LINE INDENT i = charMap [ ord ( s [ j ] ) ] + 1 NEW_LINE DEDENT charMap [ ord ( s [ j ] ) ] = j NEW_LINE max_len = max ( max_len , j - i + 1 ) NEW_LINE DEDENT return max_len NEW_LINE DEDENT DEDENT
T40390
import java . util . HashSet ; class Solution { public int numJewelsInStones ( String J , String S ) { int result = 0 ; HashSet jHash = new HashSet < > ( ) ; for ( int j = 0 ; j < J . length ( ) ; j ++ ) { jHash . add ( J . charAt ( j ) ) ; } for ( int s = 0 ; s < S . length ( ) ; s ++ ) { if ( jHash . contains ( S . charAt ( s ) ) ) { result ++ ; } } return result ; } }
class Solution ( object ) : NEW_LINE INDENT def numJewelsInStones ( self , J , S ) : NEW_LINE INDENT if len ( J ) == 0 or len ( S ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT j_set = set ( J ) NEW_LINE ans = 0 NEW_LINE for c in S : NEW_LINE INDENT if c in j_set : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT DEDENT
T40391
class Solution { public TreeNode convertBST ( TreeNode root ) { int sum = 0 ; TreeNode node = root ; Stack < TreeNode > stack = new Stack < TreeNode > ( ) ; while ( ! stack . isEmpty ( ) || node != null ) { while ( node != null ) { stack . add ( node ) ; node = node . right ; } node = stack . pop ( ) ; sum += node . val ; node . val = sum ; node = node . left ; } return root ; } }
class Solution ( object ) : NEW_LINE INDENT def convertBST ( self , root ) : NEW_LINE INDENT total = 0 NEW_LINE node = root NEW_LINE stack = [ ] NEW_LINE while stack or node is not None : NEW_LINE INDENT while node is not None : NEW_LINE INDENT stack . append ( node ) NEW_LINE node = node . right NEW_LINE DEDENT node = stack . pop ( ) NEW_LINE total += node . val NEW_LINE node . val = total NEW_LINE node = node . left NEW_LINE DEDENT return root NEW_LINE DEDENT DEDENT
T40392
public class Solution { public boolean canPlaceFlowers ( int [ ] flowerbed , int n ) { int count = 0 , curr ; for ( int i = 0 ; i < flowerbed . length ; i ++ ) { curr = flowerbed [ i ] ; if ( i - 1 >= 0 ) curr += flowerbed [ i - 1 ] ; if ( i + 1 < flowerbed . length ) curr += flowerbed [ i + 1 ] ; if ( curr == 0 ) { count ++ ; flowerbed [ i ] = 1 ; } if ( count >= n ) return true ; } return false ; } }
class Solution ( object ) : NEW_LINE INDENT def canPlaceFlowers ( self , flowerbed , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( flowerbed ) ) : NEW_LINE INDENT curr = flowerbed [ i ] NEW_LINE if i - 1 >= 0 : NEW_LINE INDENT curr += flowerbed [ i - 1 ] NEW_LINE DEDENT if i + 1 < len ( flowerbed ) : NEW_LINE INDENT curr += flowerbed [ i + 1 ] NEW_LINE DEDENT if curr == 0 : NEW_LINE INDENT count += 1 NEW_LINE flowerbed [ i ] = 1 NEW_LINE if count >= n : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT DEDENT
T40393
class Solution { public int [ ] xorQueries ( int [ ] arr , int [ ] [ ] queries ) { int [ ] res = new int [ queries . length ] , q ; for ( int i = 1 ; i < arr . length ; i ++ ) arr [ i ] ^= arr [ i - 1 ] ; for ( int i = 0 ; i < queries . length ; i ++ ) { q = queries [ i ] ; res [ i ] = q [ 0 ] > 0 ? arr [ q [ 0 ] - 1 ] ^ arr [ q [ 1 ] ] : arr [ q [ 1 ] ] ; } return res ; } }
class Solution : NEW_LINE INDENT def xorQueries ( self , arr : List [ int ] , queries : List [ List [ int ] ] ) -> List [ int ] : NEW_LINE INDENT pref = [ 0 ] NEW_LINE for e in arr : NEW_LINE INDENT pref . append ( e ^ pref [ - 1 ] ) NEW_LINE DEDENT ans = [ ] NEW_LINE for [ l , r ] in queries : NEW_LINE INDENT ans . append ( pref [ r + 1 ] ^ pref [ l ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT
T40394
class Solution { private int result ; private HashMap < Integer , Integer > cache ; public int pathSum ( TreeNode root , int sum ) { result = 0 ; cache = new HashMap < Integer , Integer > ( ) ; cache . put ( 0 , 1 ) ; pathSumHelper ( root , sum , 0 ) ; return result ; } private void pathSumHelper ( TreeNode root , int target , int soFar ) { if ( root != null ) { int complement = soFar + root . val - target ; if ( cache . containsKey ( complement ) ) result += cache . get ( complement ) ; cache . put ( soFar + root . val , cache . getOrDefault ( soFar + root . val , 0 ) + 1 ) ; pathSumHelper ( root . left , target , soFar + root . val ) ; pathSumHelper ( root . right , target , soFar + root . val ) ; cache . put ( soFar + root . val , cache . get ( soFar + root . val ) - 1 ) ; } } }
class Solution ( object ) : NEW_LINE INDENT def pathSumHelper ( self , root , target , so_far , cache ) : NEW_LINE INDENT if root : NEW_LINE INDENT complement = so_far + root . val - target NEW_LINE if complement in cache : NEW_LINE INDENT self . result += cache [ complement ] NEW_LINE DEDENT cache [ so_far + root . val ] = cache . get ( so_far + root . val , 0 ) + 1 NEW_LINE self . pathSumHelper ( root . left , target , so_far + root . val , cache ) NEW_LINE self . pathSumHelper ( root . right , target , so_far + root . val , cache ) NEW_LINE cache [ so_far + root . val ] -= 1 NEW_LINE DEDENT return NEW_LINE DEDENT def pathSum ( self , root , sum ) : NEW_LINE INDENT self . result = 0 NEW_LINE self . pathSumHelper ( root , sum , 0 , { 0 : 1 } ) NEW_LINE return self . result NEW_LINE DEDENT DEDENT
T40395
class Solution { public int maximum69Number ( int num ) { return Integer . valueOf ( String . valueOf ( num ) . replaceFirst ( "6" , "9" ) ) ; } }
class Solution : NEW_LINE INDENT def maximum69Number ( self , num : int ) -> int : NEW_LINE INDENT return ( str ( num ) . replace ( '6' , '9' , 1 ) ) NEW_LINE DEDENT DEDENT
T40396
import java . util . HashSet ; class Solution { public int numUniqueEmails ( String [ ] emails ) { HashSet < String > emailSet = new HashSet < > ( ) ; for ( String email : emails ) { String firstSplit [ ] = email . split ( " @ " ) ; String secondSplit [ ] = firstSplit [ 0 ] . replaceAll ( " . " , " " ) . split ( " [ + ] " ) ; emailSet . add ( secondSplit [ 0 ] + firstSplit [ 1 ] ) ; } return emailSet . size ( ) ; } }
class Solution ( object ) : NEW_LINE INDENT def numUniqueEmails ( self , emails ) : NEW_LINE INDENT email_set = set ( ) NEW_LINE for email in emails : NEW_LINE INDENT elements = email . split ( ' @ ' ) NEW_LINE email_set . add ( elements [ 0 ] . split ( ' + ' ) [ 0 ] . replace ( ' . ' , ' ' ) + elements [ 1 ] ) NEW_LINE DEDENT return len ( email_set ) NEW_LINE DEDENT DEDENT
T40397
class Solution { public boolean isRectangleOverlap ( int [ ] rec1 , int [ ] rec2 ) { return ( Math . min ( rec1 [ 2 ] , rec2 [ 2 ] ) > Math . max ( rec1 [ 0 ] , rec2 [ 0 ] ) && Math . min ( rec1 [ 3 ] , rec2 [ 3 ] ) > Math . max ( rec1 [ 1 ] , rec2 [ 1 ] ) ) ; } }
class Solution ( object ) : NEW_LINE INDENT def isRectangleOverlap ( self , rec1 , rec2 ) : NEW_LINE INDENT return not ( rec1 [ 2 ] <= rec2 [ 0 ] or rec1 [ 3 ] <= rec2 [ 1 ] or rec1 [ 0 ] >= rec2 [ 2 ] or rec1 [ 1 ] >= rec2 [ 3 ] ) NEW_LINE DEDENT DEDENT
T40398
class Solution { public int hammingDistance ( int x , int y ) { return Integer . bitCount ( x ^ y ) ; } }
class Solution ( object ) : NEW_LINE INDENT def hammingDistance ( self , x , y ) : NEW_LINE INDENT return bin ( x ^ y ) . count ( '1' ) NEW_LINE DEDENT DEDENT
T40399
class Solution { public void duplicateZeros ( int [ ] arr ) { int movePos = 0 ; int lastPos = arr . length - 1 ; for ( int i = 0 ; i <= lastPos - movePos ; i ++ ) { if ( arr [ i ] == 0 ) { if ( i == lastPos - movePos ) { arr [ lastPos ] = 0 ; lastPos -- ; break ; } movePos ++ ; } } lastPos = lastPos - movePos ; for ( int i = lastPos ; i >= 0 ; i -- ) { if ( arr [ i ] == 0 ) { arr [ i + movePos ] = 0 ; movePos -- ; arr [ i + movePos ] = 0 ; } else { arr [ i + movePos ] = arr [ i ] ; } } } }
class Solution : NEW_LINE INDENT def duplicateZeros ( self , arr : List [ int ] ) -> None : NEW_LINE INDENT move_pos = 0 NEW_LINE last_pos = len ( arr ) - 1 NEW_LINE for i in range ( last_pos + 1 ) : NEW_LINE INDENT if i > last_pos - move_pos : NEW_LINE INDENT break NEW_LINE DEDENT if arr [ i ] == 0 : NEW_LINE INDENT if i == last_pos - move_pos : NEW_LINE INDENT arr [ last_pos ] = 0 NEW_LINE last_pos -= 1 NEW_LINE break NEW_LINE DEDENT move_pos += 1 NEW_LINE DEDENT DEDENT last_pos -= move_pos NEW_LINE for i in range ( last , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT arr [ i + move_pos ] = 0 NEW_LINE move_pos -= 1 NEW_LINE arr [ i + move_pos ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i + move_pos ] = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT