首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Integer 种中的一些方法

2012-10-08 
Integer 类中的一些方法1,计算一个正int数有几位的方法: 亮点:通过维护一个数组提高性能?????final?static

Integer 类中的一些方法

1,计算一个正int数有几位的方法:

亮点:通过维护一个数组提高性能

?

????final?static?int?[]?sizeTable?=?{?9,?99,?999,?9999,?99999,?999999,?9999999,

??????????????????????????????????????99999999,?999999999,?Integer.MAX_VALUE?};

?

????//?Requires?positive?x

????static?int?stringSize(int?x)?{

????????for?(int?i=0;?;?i++)

????????????if?(x?<=?sizeTable[i])

????????????????return?i+1;

}

?

?

2,?int?值的位数放到对应的数组?buf

亮点:通过位移的方式替代十进制计算的方式,提高性能。

static?void?getChars(int?i,?int?index,?char[]?buf)?{

????????int?q,?r;

????????int?charPos?=?index;

????????char?sign?=?0;

?

????????if?(i?<?0)?{?

????????????sign?=?'-';

????????????i?=?-i;

????????}

?

????????//?Generate?two?digits?per?iteration

????????while?(i?>=?65536)?{

????????????q?=?i?/?100;

????????//?really:?r?=?i?-?(q?*?100);

????????????r?=?i?-?((q?<<?6)?+?(q?<<?5)?+?(q?<<?2));

????????????i?=?q;

????????????buf?[--charPos]?=?DigitOnes[r];

????????????buf?[--charPos]?=?DigitTens[r];

????????}

?

????????//?Fall?thru?to?fast?mode?for?smaller?numbers

????????//?assert(i?<=?65536,?i);

????????for?(;;)?{?

????????????q?=?(i?*?52429)?>>>?(16+3);

????????????r?=?i?-?((q?<<?3)?+?(q?<<?1));??//?r?=?i-(q*10)?...

????????????buf?[--charPos]?=?digits?[r];

????????????i?=?q;

????????????if?(i?==?0)?break;

????????}

????????if?(sign?!=?0)?{

????????????buf?[--charPos]?=?sign;

????????}

}

?

?

热点排行