Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.
팩토리얼을 구하고 0의 갯수를 세면... 타임 초과가 난다 이틀 연속 타임 초과
public static int zeros(int n) {
if(n==0) return 0;
BigInteger ten = new BigInteger("10");
BigInteger fact = Stream.iterate(BigInteger.ONE, x->x.add(BigInteger.ONE)).limit(n).reduce(BigInteger::multiply).get();
int trail = 0;
while(fact.divideAndRemainder(ten)[1] == BigInteger.ZERO) {
fact = fact.divide(ten);
trail++;
}
return trail;
}
시간 고려해서 한 풀이
public static int zeros(int n) {
int trail = 0;
int i = 1;
double temp = 0d;
do {
temp = n / Math.pow(5, i++);
trail += Math.floor(temp);
}while(temp > 0);
return trail;
}
The year is 1214. One night, Pope Innocent III awakens to find the the archangel Gabriel floating before him. Gabriel thunders to the pope:
Gather all of the learned men in Pisa, especially Leonardo Fibonacci. In order for the crusades in the holy lands to be successful, these men must calculate the millionth number in Fibonacci's recurrence. Fail to do this, and your armies will never reclaim the holy land. It is His will.
The angel then vanishes in an explosion of white light.
Pope Innocent III sits in his bed in awe. How much is a million? he thinks to himself. He never was very good at math.
He tries writing the number down, but because everyone in Europe is still using Roman numerals at this moment in history, he cannot represent this number. If he only knew about the invention of zero, it might make this sort of thing easier.
He decides to go back to bed. He consoles himself, The Lord would never challenge me thus; this must have been some deceit by the devil. A pretty horrendous nightmare, to be sure.
Pope Innocent III's armies would go on to conquer Constantinople (now Istanbul), but they would never reclaim the holy land as he desired.
In this kata you will have to calculate fib(n) where:
fib(0) := 0
fib(1) := 1
fin(n + 2) := fib(n + 1) + fib(n)
Write an algorithm that can handle n where 1000000 ≤ n ≤ 1500000.
Your algorithm must output the exact integer answer, to full precision. Also, it must correctly handle negative numbers as input.
HINT I: Can you rearrange the equation fib(n + 2) = fib(n + 1) + fib(n) to find fib(n) if you already know fin(n + 1) and fib(n + 2)? Use this to reason what value fib has to have for negative values.
HINT II: See http://mitpress.mit.edu/sicp/chapter1/node15.html
타임오버 나왔다. 대칭이용해서 음수 까지는 잘처리했는데 피보나치 구하는 방식자체가 틀린것 같다.
import java.math.BigInteger;
import java.util.stream.Stream;
public class Fibonacci {
public static BigInteger fib(BigInteger n) {
// ...
if(n.signum() == 0) {
return BigInteger.ZERO;
}
BigInteger result = Stream.iterate(new BigInteger []{ BigInteger.ONE, BigInteger.ONE }, p-> new BigInteger[]{ p[1], p[0].add(p[1]) }).limit(n.abs().longValue()).reduce((a, b) -> b).get()[0];
if(n.signum() == -1 && n.abs().mod(new BigInteger("2")).equals(BigInteger.ZERO)) return result.negate();
return result;
}
}
##Do you know how to make a spiral? Let's test it!
Classic definition: A spiral is a curve which emanates from a central point, getting progressively farther away as it revolves around the point.
Your objective is to complete a function createSpiral(N) that receives an integer N and returns an NxN two-dimensional array with numbers 1 through N^2 represented as a clockwise spiral.
Return an empty array if N < 1 or N is not int/number
Examples:
N = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
1 2 3
8 9 4
7 6 5
N = 4 Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
N = 5 Output: [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,10,9]]
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
public class TheClockwiseSpiral {
public static int[][] createSpiral(int N) {
// your code here
int[][] result = new int [N][N];
int element =1;
int i=0;
int j=0;
int k=0;
int n=N;
for(;n>0;n-=2){
for(i=0;i<n;i++){
result[j][j+i]=element;
element++;
}
for(k=1;k<n;k++){
result[j+k][N-j-1]=element;
element++;
}
for(i=1;i<n;i++){
result[j+k-1][N-1-j-i]=element;
element++;
}
for(k=1;k<n-1;k++){
result[N-1-j-k][j]=element;
element++;
}
j++;
}
return result;
}
}
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized.
Examples:
// returns "theStealthWarrior"
toCamelCase("the-stealth-warrior")
// returns "TheStealthWarrior"
toCamelCase("The_Stealth_Warrior")
오늘은 그나마 빨리 풀었다. 5랑 4레벨 차이가 어마어마한듯 ㅠ
import java.lang.StringBuilder;
import java.util.StringTokenizer;
class Solution{
static String toCamelCase(String s){
StringTokenizer tokenizer = new StringTokenizer(s,"-|_|");
StringBuilder result = new StringBuilder();
int index = 0;
while(tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if(index ==0) {
result.append(token);
}else {
result.append(token.substring(0, 1).toUpperCase() + token.substring(1));
}
index++;
}
return result.toString();
}
}
We need a reusable program to encode/decode text to unicode value as represented in Java and vice-versa.
Encoder:
Input
"hola"
Output
"\u0068\u006f\u006c\u0061"
Decoder:
Input
"\u0068\u006f\u006c\u0061"
Output
"hola"
Observations:
Please note that unicode values have always a back slash \ the letter u and 4 hexadecimal digits corresponding to the value in the unicode character set.
Codewars has some trouble showing non ASCII characters so perhaps you should try it locally first.
import java.io.UnsupportedEncodingException;
public class JavaUnicodeEncoder {
public static String decode(final String input) throws UnsupportedEncodingException {
String[] arr = input.replace("\\","").split("u");
StringBuilder result = new StringBuilder();
for(String str :arr){
if(str.length()!=0) {
int hex = Integer.parseInt(str, 16);
result.append((char)hex);
}
}
return result.toString();
}
public static String encode(String input){
StringBuilder builder = new StringBuilder();
for (char c : input.toCharArray()) {
builder.append("\\u" + Integer.toHexString(c | 0x10000).substring(1));
};
return builder.toString();
}
}
Here's a seemingly simple challenge. We're giving you a class called bagel, exactly as it appears below. All it really does is return an int, specifically 3.
public class Bagel {
public final int getValue() {
return 3;
}
}
The catch? For the solution, we're testing that the result is equal to 4. But as a little hint, the solution to the this Kata is exactly the same as the example test cases.
통과조건...
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class BagelTest {
@Test
public void testBagel() {
Bagel bagel = BagelSolver.getBagel();
assertEquals(
bagel.getValue() == 4,
java.lang.Boolean.TRUE
);
}
}
...별짓을 다했다 리플랙션 , 프록시, bci
설마이걸까 했는데 -.- 으음 빡친다.
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class BagelSolver {
public static Bagel getBagel() {
try {
Field f = Boolean.class.getField("TRUE");
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
modifiers.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.set(null, false);
} catch (Exception e) {
// TODO: handle exception
}
return new Bagel();
}
}
Create a simple calculator that given a string of operators (+ - * and /) and numbers separated by spaces returns the value of that expression
Example:
Calculator.evaluate("2 / 2 + 3 * 4 - 6") // => 7
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
In mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120
Your mission is simple: write a function that takes an integer n and returns the value of n!.
You are guaranteed an integer argument. For any values outside the non-negative range, return null, nil or None (return an empty string "" in C and C++). For non-negative numbers a full length number is expected for example, return 25! = "15511210043330985984000000" as a string.
BigInteger가 없었다면 꽤나 어려울것 같지만
다른 사람들 풀이를 봐도 대다수가 BigInteger 를이용해서 풀었더라.
import java.math.BigInteger;
public class Kata
{
public static String Factorial(int n) {
BigInteger result = BigInteger.valueOf(1);
for (int i = 1; i <= n; i++)
result = result.multiply(BigInteger.valueOf(i));
return result.toString();
}
}
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.
Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act).
Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea.
You are now to create a function that returns a Josephus permutation, taking as parameters the initial array/list of items to be permuted as if they were in a circle and counted out every k places until none remained.
Tips and notes: it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1.
For example, with n=7 and k=3 josephus(7,3) should act this way.
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out and goes into the result [3]
[1,2,4,5,7] => 6 is counted out and goes into the result [3,6]
[1,4,5,7] => 2 is counted out and goes into the result [3,6,2]
[1,4,5] => 7 is counted out and goes into the result [3,6,2,7]
[1,4] => 5 is counted out and goes into the result [3,6,2,7,5]
[4] => 1 is counted out and goes into the result [3,6,2,7,5,1]
[] => 4 is counted out and goes into the result [3,6,2,7,5,1,4]
So our final result is: josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4]
public static <T> List<T> josephusPermutation(final List<T> items, final int k) {
int current = 0;
List<T> result= new ArrayList<T>();
while (items.size() > 0) {
current = (current-1+k)%items.size();
/*
current+=k-1;
while(current > = items.size()) {
current -= items.size();
}
*/
result.add(items.remove(current));
}
return result;
}