简体   繁体   English

如何将 int 值 09 转换为 char 数组作为 {'0','9'}?

[英]How to convert int value 09 to char array as {'0','9'}?

I am working on the problem to find the next greatest number with the same set of digits.我正在解决这个问题,以找到具有相同数字集的下一个最大数字。

For this I take a integer value input from the user and I want to convert to char array or int array so that I can access individual digits.为此,我从用户那里输入一个整数值,我想转换为 char 数组或 int 数组,以便我可以访问单个数字。

But when I take但是当我拿

int value=09 as the input and convert to char array it gives only 9 as it considers it to be octal value. int value=09 作为输入并转换为 char 数组它只给出 9 因为它认为它是八进制值。 How can I overcome this ?我怎样才能克服这个?

It is not possible convert a 09 int value to a String of 9 since the value 09 can not be stored in an int .这是不可能的一个转换09 int值的字符串9由于值09不能被存储在int

int is not capable of storing trailing zeros. int不能存储尾随零。

Take this sample.拿这个样本。

int foo = Integer.valueOf("09");
System.out.println(foo);

Output输出

9

So to solve your problem you should get a String from the user, validate it and parse it to an Integer[] .因此,要解决您的问题,您应该从用户那里获取一个String ,对其进行验证并将其解析为Integer[]

Solution解决方案

public Integer[] parseToInteger(String number) {
    return Arrays.asList(number.toCharArray())
        .stream()
        .map(c -> Integer.valueOf(c.toString()))
        .toArray(size -> new Integer[size]);
}

Now you have an Array of Integer .现在你有一个Integer Array

it is not possible in java to take the int values with leading zeros.在 java 中不可能采用带前导零的 int 值。 so for the value with leading zeros take it in string format.因此,对于带有前导零的值,将其采用字符串格式。

but we can insert zeros但我们可以插入零

int n=7;整数 n=7;
String str=String.format("%04d", n); String str=String.format("%04d", n); //4 denotes the size of the string //4 表示字符串的大小
System.out.println(str); System.out.println(str); // o/p->0007 // o/p->0007

Since leading 0's are dropped from integers there is no reason to support assigning such a value to an int.由于从整数中删除了前导 0,因此没有理由支持将这样的值分配给 int。

If I want to convert 9 to '9' I usually just add '0' to it.如果我想将9转换为'9'我通常只添加'0'到它。

You can also do the following:您还可以执行以下操作:

char c = Character.forDigit(9,10);

If you have a string of characters, you can do the following:如果您有一个字符串,您可以执行以下操作:

        String str = "09";
        List<Character> chrs =
                str.chars().mapToObj(a -> Character.valueOf((char) a))
                        .collect(Collectors.toList());
        System.out.println(chrs);

Prints印刷

[0,9]

I am working on the problem to find the next greatest number with the same set of digits.我正在研究这个问题,以找到具有相同数字集的下一个最大数字。

For this I take a integer value input from the user and I want to convert to char array or int array so that I can access individual digits.为此,我从用户那里输入一个整数值,我想转换为char数组或int数组,以便可以访问各个数字。

But when I take但是当我服用

int value=09 as the input and convert to char array it gives only 9 as it considers it to be octal value. int value = 09作为输入并转换为char数组,因为它认为它是八进制值,所以仅给出9。 How can I overcome this ?我该如何克服呢?

You are asking how to parse a number starting with a leading zero, but I get the feeling that you are actually on the worng track given the problem you are trying to resolve.您问的是如何解析以前导零开头的数字,但鉴于您要解决的问题,我觉得您实际上处于磨损轨道上。 So let's take one step backward, and lets make sure I understand your problem correctly.因此,让我们向后退一步,确保我正确理解您的问题。

You say that you have to find the "next greatest number with the same set of digits".你说你必须找到“具有相同数字集的下一个最大数字”。 So you are playing "Scrabble" with digits, trying to find the smalest number composed with the same digits that is strictly greater to the original number.因此,您正在使用数字玩“拼字游戏”,试图找到由严格大于原始数字的相同数字组成的最小数字。 For example, given the input "09", you would output "90", and for "123", you would output "132".例如,给定输入“09”,您将输出“90”,而对于“123”,您将输出“132”。 Is that right?那正确吗? Let assume so.假设如此。

Now, the real challenge here is how to determine the smalest number composed with thise digits that is stricly greater to the original number.现在,这里真正的挑战是如何确定由这个数字组成的比原始数字大得多的最小数字。 Actually, there's a few possible strategies:实际上,有几种可能的策略:

  1. Enumerate all possible permutations of those digits, then filter out those that are not strictly greater to the original number, and then, among the remaining values, find the smallest value.枚举这些数字的所有可能排列,然后过滤掉那些不严格大于原始数字的排列,然后在剩余的值中找到最小值。 That would be a very innefficient strategy, requiring both disproportionate memory and processing power.这将是一种非常低效的策略,需要不成比例的内存和处理能力。 Please, don't consider this seriously (that is, unless you are actually coding for a Quantum Computer ;) ).请不要认真考虑这一点(也就是说,除非您实际上是在为量子计算机编码;))。
  2. Set a variable to the initial number, then iteratively increment that variable by one until you eventually get a number that is composed of the same digits as the original values.将变量设置为初始数字,然后将该变量迭代地递增 1,直到最终得到一个由与原始值相同的数字组成的数字。 That one might look simple to implement, but it actually hides some complexities (ie determining that two numbers are composed from the same digits is not trivial , special handling would be required to avoid endless loop if the initial number is actually the greatest value that can be formed with those digits).那个可能看起来很容易实现,但它实际上隐藏了一些复杂性(即确定两个数字由相同的数字组成并不是微不足道的,如果初始数字实际上是最大的值,则需要特殊处理以避免无限循环由这些数字组成)。 Anyway, this strategy would also be rather innefficient, requiring considerable processing power.无论如何,这种策略也相当低效,需要相当大的处理能力。
  3. Iterate over the digits themselves, and determine exactly which digits have to be swapped/reordered to get the next number.迭代数字本身,并准确确定哪些数字必须交换/重新排序以获得下一个数字。 This is actually very simple to implement (I just wrote it in less that 5 minutes), but require some thinking first.这实际上很容易实现(我只是在不到 5 分钟的时间内编写了它),但首先需要一些思考。 The algorithm is O(n log n), where n is the length of the number (in digits).该算法是 O(n log n),其中 n 是数字的长度(以数字为单位)。 Take a sheet of paper, write example numbers in columns, and try to understand the logic behind it.拿一张纸,在列中写下示例数字,并尝试理解其背后的逻辑。 This is definitely the way to go.这绝对是要走的路。

All three strategies have one thing in common: they all require that you work (at some point at least) with digits rather than with the number itself.这三种策略都有一个共同点:它们都要求您(至少在某个时候)使用数字而不是数字本身。 In the last strategy, you actually never need the actual value itself.在最后一个策略中,您实际上永远不需要实际值本身。 You are simply playing Scrabble, with digits rather than letters.你只是在玩拼字游戏,用数字而不是字母。

So assuming you indeed want to implement strategy 3, here is what your main method might looks like (I wont expand more on this one, comments should be far enough):因此,假设您确实想要实施策略 3,那么您的main方法可能如下所示(我不会对此进行更多扩展,评论应该足够了):

public static void main(String[] args) {

    // Read input number and parse it into an array of digit
    String inputText = readLineFromUser();
    int[] inputDigits = parseToDigits(inputText);

    // Determine the next greater number
    int[] outputDigits = findNextGreaterNumber(inputDigits);

    // Output the resulting value
    String outputText = joinDigits(outputDigits);
    println(outputText);
}

So here's the point of all this discussion: the parseToDigits method takes a String and return an array of digits (I used int here to keep things simpler, but byte would actually have been enough).所以这就是所有讨论的重点: parseToDigits方法接受一个String并返回一个数字数组(我在这里使用int使事情更简单,但实际上byte就足够了)。 So basically, you want to take the characters of the input string, and convert that array to an array of integer, with each position in the output containing the value of the corresponding digit in the input.所以基本上,您想要获取输入字符串的字符,并将该数组转换为整数数组,输出中的每个位置都包含输入中相应数字的值。 This can be written in various ways in Java, but I think the most simple would be with a simple for loop:这可以在 Java 中以多种方式编写,但我认为最简单的是使用简单的for循环:

public static int[] parseToDigits(String input) {

    char[] chars = input.toCharArray();
    int[] digits = new int[chars.length];

    for (int i = 0 ; i < chars.length ; i++)
        digits[i] = Character.forDigit(chars[i], 10);

    return digits;
}

Note that Character.forDigit(digit, radix) returns the value of character digit in base radix ;注意, Character.forDigit(digit, radix)返回字符的值digit在碱radix ; if digit is not valid for the given base, forDigit returns 0 .如果digit对于给定的基数无效,则forDigit返回0 For simplicity, I'm skipping proper validation checking here.为简单起见,我在这里跳过了正确的验证检查。 One could consider calling Character.isDigit(digit, radix) first to determine if a digit is acceptable, throwing an exception if it is not.可以考虑首先调用Character.isDigit(digit, radix)来确定一个数字是否可以接受,如果不是则抛出异常。

As to the opposite opperation, joinDigits , it would looks like:至于相反的操作, joinDigits ,它看起来像:

public static String joinDigits(int[] digits) {
    char[] chars = new char[digits.length];

    for (int i = 0 ; i < digits.length ; i++)
        chars[i] = Character.digit(digits[i], 10);

    return new String(chars);
}

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM