问题
I came across this interview question where the interviewer asked to write a function which will take an integer, say 123, and will return a string that would be how one would say that integer.In above case output should be "one hundred and twenty three".I have no idea how to solve these problems.Can anyone help in how to work out this problem? A pseudo code will be helpfull.
回答1:
Use this Code for Converting Numbers to Word Source here
public class YourNumberMyWord {
public void pw(int n,String ch) {
String one[]={" "," one"," two"," three"," four"," five"," " +
"six"," seven"," eight"," Nine"," ten"," eleven"," twelve"," " +
"thirteen"," fourteen","fifteen"," sixteen"," seventeen"," eighteen"," nineteen"};
String ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","seventy"," eighty"," ninety"};
if(n>19) {
System.out.print(ten[n/10]+" "+one[n%10]);
}
else {
System.out.print(one[n]);} if(n>0)System.out.print(ch);
}
public static void main(String[] args) {
int n=0; Scanner scanf = new Scanner(System.in);
System.out.println("Enter an integer number: ");
n = scanf.nextInt();
if(n<=0)
System.out.println("Enter numbers greater than 0");
else {
YourNumberMyWord a = new YourNumberMyWord();
a.pw((n/1000000000)," Hundred"); a.pw((n/10000000)%100," crore");
a.pw(((n/100000)%100)," lakh"); a.pw(((n/1000)%100)," thousand");
a.pw(((n/100)%10)," hundred"); a.pw((n%100)," ");
}
}
}
回答2:
Here is the solution to your problem:
Numbers to words
It is not as simple as you may imagine.
回答3:
Use the same convertLessThanOneThousand function written earlier.
private static String pronounce(int number) {
String result = "";
int cnt = 0;
while (number != 0) {
int rem = number % 1000;
result = convertLessThanOneThousand(rem) + result;
number = number / 1000;
cnt++;
if (number != 0) {
switch (cnt) {
case 1:
result = " thousand " + result;
break;
case 2:
result = " million " + result;
break;
case 3:
result = " billion " + result;
break;
}
}
}
return result;
}
回答4:
This is my code of converting an int to its English words. Hope it helps.
public class Excercise1 {
static String words[]={"One","Two","Three","Four","Five", "Six", "Seven", "Eight", "Nine", "Ten"};
public static void main(String[] args){
String inputValue = JOptionPane.showInputDialog("Please input a value");
int num = Integer.parseInt(inputValue.toString());
if(num <= 10){
System.out.println(words[num-1]);
} else {
JOptionPane.showMessageDialog(null, "You must put number 1 - 10", "alert", JOptionPane.ERROR_MESSAGE);
}
}
}
回答5:
there are number of ways..as of now
1.String.valueOf(intVarable)
2.Integer.toString(intVarable)
public class ConvertIntToString {
public static void main(String[] args) {
int aInt = 1;
String aString = Integer.toString(aInt);
}
}
来源:https://stackoverflow.com/questions/21521520/how-to-convert-an-int-so-as-to-return-the-string-which-is-how-we-say-the-int