주요 Issue : 부동소수점 연산문제

double - 1x 자리 이상인경우 오차 ->해결책 BigDecimal사용

class Solution {//시작시칸 20:40경
    public long solution(long n) {
        long first=0;//3진법저장
        long second=0;//앞뒤반전저장
        long answer = 0;//10진법 표현값
        long temp=1; long temp2=0;  long size=0;
        while(n>=1)//3진법으로
        {
            first+=n%3*temp;
            temp=temp*10;
            n=n/3; 
            ++size;//자릿수
        }
        
        System.out.println(first+" "+size);   
             while(size>=0)//반대로돌리기
        {
             System.out.println(first+ " "+second+" "+size);  
             second+=(first%10)*(long)Math.pow(10,size-1);//Math.pow(10,size);
             //System.out.println(first+ " "+second+" "+size);  
             first/=10;        
            --size;
        }      
   // second+=Math.pow(10,0);
        while(second>0)//3진법 10진법으로 표현
        {
            answer+=(second%10)*Math.pow(3,temp2);
            second/=10;
        //    second=Math.floor(second);
            temp2++;
            System.out.println(answer+"임");
        }

        return answer;

    }
}

Math.pow(10,size-1)의 반환값이 실수형이기때문에 10번째 예제가 오류가 떳다. 형변환을통해 정수로 바꾸어서 해결하였다.

부동소수점예시

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;


public class aa {

    public static void main(String[] args) throws IOException{
long a = 2;
double b =1.0;
long z=1;
long c=200000;
long test=0;
for(int i=0;i<19;i++)
{
    a*=10;
}
a+=1;
    System.out.println(a+"이다~! "+(a+b)+"이다~!  "+a%10+" "+(a+b)%10+"이다 "+(a+z)%10);
    System.out.println(a+b);
    System.out.println(c+b+ " "+(c+b)%10);
    }

}

정수형에 실수형을 더하면 1.xx*10e형식으로 변하고 소수 16자리?까지 값 보장이 안되므로 수의 길이가 길면 값이 제대로 더해지지 않는다.

다른사람풀이

나와는 다르게 문자열로 보고 문제를 해결함

class Solution {
    public int solution(int n) {
        String a = "";

        while(n > 0){
            a = (n % 3) + a;
            n /= 3;
        }
        a = new StringBuilder(a).reverse().toString();


        return Integer.parseInt(a,3);
    }
}

 

필요한부분

->부동소수점에대해 한번 살펴보기

+ Recent posts