함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요.
@@처음 내가 짠 코드
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
for(int i=0; i<n;i++){
answer[(i)]=(long)(x*(i+1));
}
return answer;
}
}
@@답
class Solution {
public long[] solution(int x, int n) {
long[] answer = new long[n];
for(int i=0; i<n;i++){
answer[(i)]=(long)x*(i+1);
}
return answer;
}
}
1.int형끼리 곱하면 long형으로 변환이 일어나기전 int형 범위를 넘어서서 오류가 날 수 있다.
2.long형 * int형은 long형이 되기 때문에 하나만 형변환 해주면된다.
======================================================================
자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.
@@내가 쓴 답
class Solution {
public int[] solution(long n) {
int[] ex = new int[11];
int i=0;
while(true){
if(n!=0){
ex[i]=(int)(n%10);
n=n/10;
i++;
}else{
break;
}
}
int[] answer = new int[i];
for(int j=0; j<i ;j++){
answer[j] = ex[j];
}
return answer;
}
}
@@다른 분의 깔끔한 정답
import java.util.stream.IntStream;
class Solution {
public int[] solution(long n) {
return new StringBuilder().append(n).reverse().chars().map(Character::getNumericValue).toArray();
}
}
@@또 다른 분의 정답
class Solution {
public int[] solution(long n) {
String a = "" + n;
int[] answer = new int[a.length()];
int cnt=0;
while(n>0) {
answer[cnt]=(int)(n%10);
n/=10;
System.out.println(n);
cnt++;
}
return answer;
}
}
@@ long형을( "" + )로 바로 String형으로 변형하고 String의 .length로 배열 크기를 정하는것!!!!!!!!!!