注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
原书中bit manipulation的solution是基于26个字符a-z的,这样java中的一个int 32bit就可以实现字符到每一个bit的mapping。
如果题目改成256个asc字符,一下是我的改动结果:
public static boolean isUniqueChars256(String str) {
if (str.length() > 256) {
return false;
}
int[] checker = new int[8];
for (int i = 0; i < str.length(); i++) {
// value is the distance from the first char which is null
int val = str.charAt(i) - '\u0000';
int idx=val/32,shift=val%32;
if (Math.abs((checker[idx] & (1 << shift))) != 0) return false;
checker[idx] |= (1 << shift);
}
return true;
}
程序貌似可以,就是return false那行有个小问题。因为java的int是必须带符号的,这样Math.abs(-2,147,483,648)=-2,147,483,648。所以只能用上abs和!=0做为condition了。
我想知道,abs不能用在smallest int上这个是不是有些不合理呢。
本人基础较差,以前写程序不求甚解,请指教。
|