转换为Java的Python不能正确返回

2024-07-04 10:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试转换python代码,当给定一个数字时,我们将根据给定的数字返回一个字符串,以正确加权这两个数字:

def answer(weight):
    instructions = []
    steps = number_of_steps(weight)

    for n in xrange(steps):
        i = instruction_index(n, weight)
        instructions.append(['-', 'R', 'L'][i])

    return instructions


def number_of_steps(weight):
    return int(log(weight * 2, 3)) + 1


def instruction_index(n, weight):
    offset = (3 ** n - 1) / 2

    corrected = int((weight + offset) / 3 ** n)

    return corrected % 3

我试着用以下代码将其转换为java:

import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Math.*;

public class Answer {   

    public static String[] answer(int weight) { 

        ArrayList<String> listOfWeightLocations = new ArrayList<String>();
        int numberOfSteps = numberOfSteps(weight);
        String[] pattern = {"-", "R", "L"};

        for (int index = 0; index <= numberOfSteps; index++) {
            int solution = instructions(index, weight);
            listOfWeightLocations.add(pattern[solution] + 1); //Add one
        }

        String[] listAnswer = listOfWeightLocations.toArray(new String[listOfWeightLocations.size()]);
        return listAnswer;
    }

    public static int numberOfSteps(int weight) {
        int numOfSteps = (int) Math.floor(logOfBase(weight * 2, 3)) + 1;
        return numOfSteps;
    }

    public static double logOfBase(int base, int num) {
        return Math.log(num) / Math.log(base);
    }

    public static int instructions(int index, int weight) {
        double offset = (Math.pow(3, index) - 1)  / 2;
        int corrected = (int) Math.floor((weight + offset) / Math.pow(3, index));

        return (corrected % 3);
    }
}

但每次都返回错误的值。在改装过程中是否有故障,能否修复?很抱歉,有很多代码,还有一个没有税的问题,但我真的需要帮助。谢谢你


Tags: stringindexreturnstaticmathjavapublicsteps

热门问题