将多个字符串转换为一个然后解析为int

时间:2016-09-18 18:16:36

标签: java string parseint typecast-operator

我知道这不是查找回文的最简单方法...但我希望有人可以告诉我是否有办法将多个整数字符串转换为单个整数。也许从其他人那里构建一个字符串?下面我有一个输出可以反转你输入的数字。但是,它是一串独立的整数。我是否能够将其转换为单个int然后以某种方式将其与原始数字联系起来? 如果我忽略了与此相似的话题,我很抱歉。我查了一下,没找到一个明确解决了我的问题。

import java.util.Scanner;

public class Palindrone{

  public static void main(String[] args) {

  Scanner input = new Scanner(System.in);

  System.out.print("Enter an integer between 2 and 6 digits:");
  int num1 = input.nextInt();

  int rev = 0;
  //find last number
  if(num1 >= 10){
    rev = num1%10;
    System.out.print(rev);
  }
  //find 2nd to last and 3rd from last
  if(num1 >= 100){
    rev = num1%100/10;
    System.out.print(rev);
    rev = num1%1000/100;
    System.out.print(rev);
  }
  //find 4th from last
  if(num1 >= 1000){
    rev = num1%10000/1000;
    System.out.print(rev);
  }
  //find 5th
  if(num1 >= 10000){
    rev = num1%100000/10000;
    System.out.print(rev);
  }
  //find 6th
  if(num1 >= 100000){
    rev = num1%1000000/100000;
    System.out.print(rev);
  } 
 }      
}  

我正试图从打印字符串(int rev)(int rev)(int rev)(int rev)转到 一个实心字符串然后转换为int。然后if(newInt == num1)运行语句。

2 个答案:

答案 0 :(得分:1)

你可以这样做而不必担心string-int转换:

Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 2 and 6 digits: ");
String number = input.next();        
System.out.println(new StringBuilder(number).reverse()); //prints reverse number

答案 1 :(得分:0)

简单,以下方法使用Guava执行各个步骤:

public static boolean palindrome(int number) {
    // Split into an array of digits and reverse
    List<String> digits = Lists.transform(
            Lists.reverse(
                    Lists.transform(
                            Lists.transform(
                                    Lists.charactersOf(Integer.toString(number)),
                                    Functions.toStringFunction()),
                            Ints.stringConverter())),
            Ints.stringConverter().reverse());

    // Join the strings and parse to an integer
    int result = Integer.parseInt(Joiner.on("").join(digits));

    // And check if a palindrome
    return (result == number);
}

因此,如果在开头创建一个空列表,则可以对代码使用相同的技术,并将每个已解析的整数添加到列表的末尾。但是,您使用模数运算符的方式是固定的数字序列,每次乘以10是有限的。相反,如果您想使用此解析方法,请考虑使用循环:

List<Integer> digits = Lists.newArrayList();
while (number > 10) {
    int digit = number % 10;
    digits.add(digit);
    number /= 10;
}

然后反转并转换回字符串列表,并转换为整数:

List<String> strings = Lists.transform(
        Lists.reverse(digits),
        Ints.stringConverter().reverse());
int result = Integer.parseInt(Joiner.on("").join(strings));   

再次检查与原始号码是否相等。

相关问题