首页 > 代码库 > 【HDOJ】1314 Numerically Speaking
【HDOJ】1314 Numerically Speaking
学了几天的Java了,终于独立A了一道大数计算。感觉还得练Java啊。
1 import java.util.Scanner; 2 import java.math.BigInteger; 3 import java.lang.StringBuilder; 4 5 public class Main { 6 public static void main(String[] args) { 7 Scanner cin = new Scanner(System.in); 8 while (cin.hasNextLine()) { 9 String line = cin.nextLine();10 char l0 = line.charAt(0);11 if (l0 == ‘*‘)12 break;13 if (l0>=‘0‘ && l0<=‘9‘) {14 StringBuilder builder = new StringBuilder();15 BigInteger x = new BigInteger(line);16 BigInteger div = new BigInteger("26");17 BigInteger[] vals = new BigInteger[2];18 while (x.compareTo(BigInteger.ZERO) != 0) {19 vals = x.divideAndRemainder(div);20 char ch = (char)(vals[1].intValue()+96);21 builder.append(ch);22 x = vals[0];23 }24 builder.reverse();25 String ans = new String(builder.toString());26 System.out.print(ans);27 int l = ans.length();28 while (l < WIDTH) {29 System.out.print(‘ ‘);30 ++l;31 }32 } else {33 int length = line.length();34 System.out.print(line);35 int l = length;36 while (l < WIDTH) {37 System.out.print(‘ ‘);38 ++l;39 }40 BigInteger div = new BigInteger("26");41 BigInteger sum = new BigInteger(String.valueOf((int)(line.charAt(length-1))-96));42 for (int i=length-2; i>=0; --i) {43 // System.out.print("current sum = ");44 // System.out.println(sum.toString());45 BigInteger tmp = div.multiply(new BigInteger(String.valueOf((int)(line.charAt(i))-96)));46 sum = sum.add(tmp);47 div = div.multiply(new BigInteger("26"));48 }49 line = new String(sum.toString());50 }51 int length = line.length();52 int x = length%3;53 x = (x==0) ? 3:x;54 int j = 0;55 for (int i=0; i<length; ++i) {56 if (i < x) {57 System.out.print(line.charAt(i));58 } else {59 if ((j+1)<length && (j%3)==0) {60 System.out.print(‘,‘);61 }62 ++j;63 System.out.print(line.charAt(i));64 }65 }66 System.out.println();67 }68 }69 public static void reverse(byte[] bytes, int l) {70 byte tmp;71 for (int i=0; i+i<l; ++i) {72 tmp = bytes[i];73 bytes[i] = bytes[l-1-i];74 bytes[l-1-i] = tmp;75 }76 }77 static final int WIDTH = 22;78 }
【HDOJ】1314 Numerically Speaking
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。